在下面的SSCCE中,为什么catch
块一次又一次地执行,导致无限循环?
当我运行此程序并提示输入整数时,我输入a
。
我认为会发生的是InputMismatchException
会在try
块内的第一行抛出,然后控件将转到catch
块,它将打印``一次,然后进入while(true)
循环的下一次迭代,它应该再次进入try
块并且应该提示我输入整数。
但是一旦它进入while(true)
循环,似乎已经开始无休止地进入catch块,因为如果它进入try块,它会促使我再次输入一个整数。 / p>
哪里,哪个是错误?
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
输出
Please enter an integer:
a
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not ...
...
...
答案 0 :(得分:1)
因为您没有在int
块中读取不是catch
的内容(令牌)。尝试像
try {
i = reader.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.printf("%s is not an int. Please enter an integer:", reader.next());
}
调用reader.next()
(将使用令牌)就足够了。
按原样,您的Scanner
说nextInt
会导致错误,即没有int
。然后循环尝试读取int
(以及失败)。