InputMismatchException

InputMismatchException

我试图让我的而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);

最佳答案

获取InputMismatchException不会跳过错误的数据,因此下一次对nextInt()的调用将因相同的原因而失败。您应该尝试在捕获中调用nextLine()

} catch (InputMismatchException e) {
    System.out.println("That is not a number. Please try again.");
    result = false;
    user_input.nextLine(); // Advance past the bad stuff
}

09-30 17:03