【发布时间】:2014-01-21 20:17:37
【问题描述】:
这是一个很难研究的问题,所以如果这是重复的,请原谅我。
基本上,我有一个 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!");
}
}
应该发生什么,是这样的:
请扫描条码:
// And here they enter the barcode
但是却发生了这种情况:
请扫描条形码:请仅提供数字。
请扫描条形码:
编辑:
根据 Bohemian 的回答,我在代码中添加了 continue 关键字。这解决了问题,但只解决了一半。根据将我的问题搁置的人的要求(有充分的理由,正如我现在所看到的),我将为你们发布一个 SSCCE。不过,我将删除与数据库交互的方法,只保留有问题的路径:根据代码创建一个新帐户。
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.
现在发生的事情是,它说(在第一次迭代中)
请扫描条码:
但是,在完成添加帐户的过程之后,它再次循环并说:
请扫描条形码:请仅提供数字。
请扫描条形码:
编辑:
请注意,所有内容都在while 循环内,因此当用户完成所有操作后,它会返回到:
请扫描条形码:
【问题讨论】:
-
这段代码之前是什么?
-
第一次执行while循环时,在try-catch部分之后System.out.println(inCode)给你什么输出?
-
正如 Sotirios 所暗示的那样,问题很可能实际上不在此 sn-p 中。您能否发布所有代码,而不仅仅是您认为问题所在的部分?
标签: java loops input while-loop