gpt4 book ai didi

java - while 循环在提示前执行一次

转载 作者:行者123 更新时间:2023-11-30 07:11:41 25 4
gpt4 key购买 nike

这是一个很难研究的问题,所以如果这是重复的,请原谅我。

基本上,我有一个 while 循环,它只会在用户扫描的代码是整数时中断。我通过尝试 Integer.parseInt(integer) 来检查这一点,并且仅在未抛出 NumberFormatException 时才中断循环。

我的问题是,当循环第一次执行时,抛出异常,没有任何用户输入。

这是我的代码:

Scanner input = new Scanner(System.in);

while (true)
{
System.out.print("Please scan barcode: ");
int inCode = 0;

try
{
inCode = Integer.parseInt(input.next());
}
catch (NumberFormatException e)
{
System.out.println("Numbers only, please.");
}

if (inCode != 0) {
// Do Stuff
} else {
System.out.println("Code can't be zero!");
}
}

应该发生什么,是这样的:

Please scan barcode: // And here they enter the barcode

但是这会发生:

Please scan barcode: Numbers only, please.
Please scan barcode:

编辑:

根据 Bohemian 的回答,我在代码中添加了 continue 关键字。这解决了问题,但只解决了一半。根据搁置我的问题的人的要求(有充分的理由,正如我现在看到的那样),我会为你们发布一个 SSCCE。不过,我将删除与数据库接口(interface)的方法,只保留有问题的路径:根据代码创建一个新帐户。

Scanner input = new Scanner(System.in);

while (true)
{
System.out.print("Please scan barcode: ");
int inCode = 0;

try
{
inCode = Integer.parseInt(input.next());
}
catch (NumberFormatException e)
{
System.out.println("Numbers only, please.");
continue;
}

if (true) // Here it checks if an account associated with the code entered exists in the database. Because I'm having issues when it creates a new account, I've made this true.
{
System.out.println("No account associated with that code! Create one?");
System.out.print("(yes/no): ");
String answer = input.next();
if (answer.equalsIgnoreCase("yes"))
{
System.out.println("Alright.");
System.out.print("Please enter a name: ");
String name = input.next();
System.out.print("Alright. Now I'll add that to the database... ");

// Here I add that to the database. Omitted.

System.out.println("Done! Please scan again to interface.");
}
else if (answer.equalsIgnoreCase("no"))
{
System.out.println("Okay then.");
}
else
{
System.out.println("Defaulting to no.");
}
}
}
// I still haven't written the code to interface with the account.

现在发生的是,它说(在第一次迭代中)

Please scan barcode:

但是,在完成添加帐户的过程后,它再次循环并说:

Please scan barcode: Numbers only, please.
Please scan barcode:

编辑:

请注意,所有内容都在 while 循环中,因此当用户完成所有操作后,它将返回:

Please scan barcode:

最佳答案

我想你想要的是这个:

Scanner input = new Scanner(System.in);
while (true) {

System.out.print("Please scan barcode: ");
int inCode = 0;

try {
inCode = Integer.parseInt(input.next());
if (inCode != 0) {
// Do Stuff
break;
}
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
}
}

关于java - while 循环在提示前执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com