参见英文答案 > How to use Scanner to accept only valid int as input 6个
> How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner 5个
Scanner scanner = new Scanner();
int number = 1;
do
{
try
{
option = scanner.nextInt();
}
catch (InputMismatchException exception)
{
System.out.println("Integers only,please.");
}
}
while (number != 0);
尽管存在异常处理,但在给出非整数输入时,此代码将进入无限循环.它不再是Scanner在下一次迭代中暂停收集输入,而是继续抛出InputMismatchExceptions直到程序被终止.
扫描整数(或其他类型,我猜)输入,丢弃无效输入并正常继续循环的最佳方法是什么?
最佳答案