我的异常处理遇到了麻烦。如果我输入一个数字,程序运行正常,但如果输入一个字符,则创建一个无限循环。
boolean ask= true;
while(ask)
{
ask = false;
try
{
System.out.println("What is the age?");
int age = input.nextInt();
setAge(age);
}catch(InputMismatchException e) {
System.out.println("Invalid input!");
ask = true;
}
}//end while
最佳答案
尝试下面的代码:
boolean ask= false;
while(!ask)
{
try
{
System.out.println("What is the age?");
int age = input.nextInt();//does not read the newline character in your input created by hitting "Enter,"
setAge(age);
ask = true;
}catch(InputMismatchException e) {
System.out.println("Invalid input!");
input.nextLine();//consumes the \n character
}
}//end while
关于java - 为什么我的异常处理错误会导致无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848963/