我正在尝试让我的 do while block 正确运行。其中包含一个 try 和 catch block ,该 block 仅部分工作。我希望它在输入 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);
最佳答案
while (result = true)
应该是
while (result == true)
或者只是
while (result)
关于java - 做 while 与 try catch 附上的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347529/