我正在尝试验证用户在菜单上的输入。选项有 1、2、3 和 4。我正在尝试处理 InputMismatchException
输入字母时出错。我看不出我做错了什么,导致我的代码陷入无限循环。
System.out.println("What will be your starting balance?");
double startingBalance =0;
boolean check = false;
while(!check) {
try {
startingBalance = input.nextDouble();
check = true;
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
//startingBalance = 0;
//e.printStackTrace();
//check = false;
}
}
看起来它进入了catch部分,但是重复循环而不是返回到try。我尝试做 input.nextDouble();
清除输入缓冲区,但什么也没做。任何帮助将不胜感激。
最佳答案
您可以使用 input.nextLine();
清除 catch block 中的扫描仪:
while (!check) {
try {
startingBalance = input.nextDouble();
check = true;
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
input.nextLine();//this will clear your Scanner and repeat again
}
}
Can I ask why you used nextLine() as opposed to nextDouble() ?
因为nextLine
将扫描仪移动到下一行
关于java - 我的异常处理中出现无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43263085/