Java 扫描仪在循环内-输入错误时为什么不退出循环?
代码-Java 扫描仪在循环内-输入错误时为什么不退出循环?,java,Java,代码- for(int i = 0; i < count; i++) { System.out.println("Please enter a number!"); try{ numbers[i] = keyboardScanner.nextInt(); }catch(InputMismatchException ex) { System.out.println("You did not enter a number!
for(int i = 0; i < count; i++)
{
System.out.println("Please enter a number!");
try{
numbers[i] = keyboardScanner.nextInt();
}catch(InputMismatchException ex)
{
System.out.println("You did not enter a number!");
}
}
for(int i=0;i
如果您输入一个字符串,它将循环到“count”。为什么会这样 当然,它将循环直到
计数
:您捕获了异常并继续循环
当您得到该异常时,您希望将从循环中分离出来:
System.out.println("You did not enter a number!");
break;
当然,它将循环直到计数:您捕获了异常并继续循环 当您得到该异常时,您希望将从循环中分离出来:
System.out.println("You did not enter a number!");
break;
是的,休息会有帮助的。但是,我还有一个问题。为什么不设计Java语言,以便在抛出某个异常时循环不会完全执行?@Apple Grinder:因为在抛出异常后,可能有很好的理由留在循环中。这是因为异常被捕获,句号。捕获的异常不会从try-catch中抛出!!!!!是的,休息会有帮助的。但是,我还有一个问题。为什么不设计Java语言,以便在抛出某个异常时循环不会完全执行?@Apple Grinder:因为在抛出异常后,可能有很好的理由留在循环中。这是因为异常被捕获,句号。捕获的异常不会从try-catch中抛出!!!!!