我有一个非工作的do-while
循环。当我输入字符串而不是int时,它应该说“bla”并再次要求插入一个数字,但是它会一遍又一遍地发送消息文本。这段代码有什么问题?为什么我有一个永无止境的do-while循环?
boolean i = true;
do {
i = false;
try {
System.out.println("insert number");
int k = sc.nextInt();
}
catch(InputMismatchException e) {
System.out.println("test");
i = true;
}
} while (i== true);
请参阅http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html:'当扫描器抛出InputMismatchException时,扫描器不会传递导致异常的令牌,以便通过其他方法检索或跳过它。所以,当你得到一个'InputMismatchException'时,你需要跳过这个标记。 –