我正在运行一个简单的Calculator应用程序,以学习Java的异常处理。我设置了两个要处理的异常:InputMismatchException和ArithmeticException,用于除以零。
ArithmeticException被处理,并且do-while循环继续。但是在捕获到InputMismatchException之后,执行终止,而不是继续循环。
代码:
do {
result = 0;
System.out.println("Enter the expression to calculate: (eg: 4 + 5) \n");
try {
num1 = input.nextInt();
op = input.next().charAt(0);
num2 = input.nextInt();
result = a.Calc(num1, op, num2); //Calc function to calculate
System.out.println("= " + result);
} catch (InputMismatchException e) {
System.err.println("Please space out the expression");
} catch (ArithmeticException e) {
System.err.println("Cannot divide by zero");
}
System.out.println("Do you want to try again? (Y to retry)");
OP = input.next().charAt(0);
} while (OP == 'Y' || OP == 'y');
输出:
Enter the expression to calculate: (eg: 4 + 5)
4 / 0
Cannot divide by zero //Exception handled
Do you want to try again? (Y to retry)
Y //Do-while continues
Enter the question to calculate: (eg: 4 + 5)
4+5
Please space out the expression //Exception handled
Do you want to try again? (Y to retry) //Rest of the code is executed
//But the execution also terminates
预期:在InputMismatchException之后继续工作一段时间
这是正确的方法吗?
答案 0 :(得分:3)
InputMismatchException
是由于调用nextInt()
引起的,因为下一个令牌是4+5
。
失败的呼叫未使用令牌。
这意味着OP = input.next().charAt(0)
设置了OP = '4'
,如果您调试代码,这应该很明显。参见What is a debugger and how can it help me diagnose problems?和How to debug small programs。
您需要丢弃失败的令牌,例如通过在nextLine()
子句中调用catch
:
} catch (InputMismatchException e) {
System.err.println("Please space out the expression");
input.nextLine(); // Discard input(s)
} ...