如何使用Scanner处理由无效输入(InputMismatchException)引起的无限循环
作者:互联网
所以,我对这段代码感到困惑:
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleReader {
Scanner reader;
public ConsoleReader() {
reader = new Scanner(System.in);
//reader.useDelimiter(System.getProperty("line.separator"));
}
public int readInt(String msg) {
int num = 0;
boolean loop = true;
while (loop) {
try {
System.out.println(msg);
num = reader.nextInt();
loop = false;
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
}
}
return num;
}
}
这是我的输出:
Insert a integer number:
Invalid value!
Insert a integer number:
Invalid value!
…
解决方法:
根据扫描仪的javadoc:
When a scanner throws an
InputMismatchException, the scanner
will not pass the token that caused
the exception, so that it may be
retrieved or skipped via some other
method.
这意味着如果下一个标记不是int,它会抛出InputMismatchException,但令牌仍然存在.因此,在循环的下一次迭代中,reader.nextInt()再次读取相同的标记并再次抛出异常.你需要的是用它.在catch中添加reader.next()以使用令牌,该令牌无效且需要被丢弃.
...
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
reader.next(); // this consumes the invalid token
}
标签:java-util-scanner,java,infinite-loop 来源: https://codeday.me/bug/20190911/1802739.html