【发布时间】:2015-07-11 02:26:15
【问题描述】:
我正在尝试让我的 do while 块正确运行。封闭在其中的是一个 try and catch 块,它只是部分工作。我希望它在输入除 Int 以外的内容时捕获异常(InputMismatchException),并在除以零时捕获异常。如果任何一个捕获发生,那么目的是它通过 do while 循环再次返回尝试。目前,它适用于ArithmeticException,但不适用于InputMismatchException。当我输入字符而不是 Int 时,它似乎不停地循环。请帮忙。我不明白为什么一个有效,另一个无效。
int div;
boolean check = true;
while (check) {
boolean result = true;
do {
try {
System.out.println("The following operation will divide the first number by the second.");
System.out.println("Enter first number.");
example.a = user_input.nextInt();
System.out.println("Enter second number.");
example.b = user_input.nextInt();
div = example.div();
System.out.println("The result of this division is " + div);
result = true;
} catch (InputMismatchException e) {
System.out.println("That is not a number. Please try again.");
result = false;
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
result = false;
}
} while (result = true);
【问题讨论】:
标签: java