我有这段代码。我想返回到循环的开头并再次请求用户输入。然而,它总是循环不停地询问输入。我的代码有什么问题吗?谢谢
while(true){
...
try {
int choice = input.nextInt(); <<---=- this should stop and ask for input, but it always loops without stopping.
} catch (InputMismatchException e){
<< I want to return to the beginning of loop here >>
}
}
From http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28int%29 :
“如果翻译成功,扫描仪就会前进到匹配的输入。”
啊,但是如果翻译是呢?not成功的?在这种情况下,扫描仪不会前进超过任何输入。错误的输入数据仍然是下一个要扫描的数据,因此循环的下一次迭代将像前一个迭代一样失败 - 循环将不断尝试一遍又一遍地读取相同的错误输入。
为了防止无限循环,您必须超越错误数据,以便获得扫描仪可以读取为整数的数据。下面的代码片段通过调用 input.next() 来完成此操作:
Scanner input = new Scanner(System.in);
while(true){
try {
int choice = input.nextInt();
System.out.println("Input was " + choice);
} catch (InputMismatchException e){
String bad_input = input.next();
System.out.println("Bad input: " + bad_input);
continue;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)