所以,我被这段代码困住了:
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()
来消耗 token ,该 token 无效,需要丢弃。
...
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
reader.next(); // this consumes the invalid token
}
关于java - 如何使用 Scanner 处理无效输入(InputMismatchException)引起的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468254/