嘿伙计们,我有以下 while 循环,它似乎不会停止。它应该询问用户一个小时。我正在 try catch 用户未输入数字的事件。
即 输入小时: foo 您没有输入有效值
然后它应该允许用户再次输入小时值,但它会一遍又一遍地打印错误消息
private static void setTime(Clock clock){
int hours = -1;
int minutes = -1;
int seconds = -1;
Scanner scanner = new Scanner(System.in);
while(true)
{
try{
System.out.print("Enter hours: ");
hours = scanner.nextInt();
}
catch(NumberFormatException nfe){
System.out.println("Input was not an integer, please try again");
continue;
}
catch(InputMismatchException ims){
System.out.println("Input was not an integer, please try again");
continue;
}
break;
}
}
最佳答案
将 Scanner Scanner = ...
移至 while 循环中。
关于java - while 循环出错。它不会阻止 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5606462/