【问题标题】:How to prolong do... while loop after Exception catch如何在异常捕获后延长 do...while 循环
【发布时间】:2018-02-23 09:20:05
【问题描述】:

我对编程完全陌生,我遇到了一个问题,当我捕获 InputMismatchException 时,我无法返回到我的主 do while 循环。我搜索了谷歌,我无法找到并完全理解用户给出的解决方案。

我的目标是消除用户输入任何可能导致应用程序终止的字符的可能性。这就是为什么我用 try/catch 包围了几乎所有的代码。

我尝试在我的代码中添加更多循环,这一切都以两种方式结束:

  1. 在到达 catch 语句后,我的循环永远不会结束。
  2. 我被放回控制台,但没有任何反应(我仍然可以在那里输入)。

谁能解释我如何达到我的目标?我也试过 hasNextInt 希望它会再次要求我输入正确的值,但它没有。我究竟做错了什么?我调试了应用程序,我可以看到该过程从 while 跳过到我的代码末尾。

Scanner scanner = new Scanner(System.in);

System.out.print("\nChoose mode: ");

int userInput = 0;

do {
    do {
        try {
            userInput = scanner.nextInt();
            switch (userInput) {
                case 1:
                    Mode_1.multiplyTwoInteger();
                    break;
                case 2:
                    Mode_2.multiplyTwoSpecifiedValues();
                    break;
                case 3:
                    System.out.println("\nYou quit application. Goodbye :)");
                    return;
                default:
                    System.out.print("Not found! Choose again game mode: ");
            }
        } catch (Exception InputMismatchException) {
            System.out.print("Wrong input!\nChoose again:");
        }
    } while (userInput <= 0 || userInput > 3);
} while (userInput != 3);

【问题讨论】:

    标签: java loops exception try-catch do-while


    【解决方案1】:

    当您收到此异常时,您的控制台会出现此异常,nextInt() 会将其读取为错误格式并给出 InputMismatchException

    尝试重新初始化 catch 块中的 scanner 对象,例如 scanner=new Scanner(System.in); 或者您可以读取错误的输入 扫描仪.nextLine().

    尝试更改您的代码以匹配如下:

    try {
                        userInput = scanner.nextInt();
                        switch (userInput) {
                            case 1:
                                Mode_1.multiplyTwoInteger();
                                break;
                            case 2:
                                Mode_2.multiplyTwoSpecifiedValues();
                                break;
                            case 3:
                                System.out.println("\nYou quit application. Goodbye :)");
                                return;
                            default:
                                System.out.print("Not found! Choose again game mode: ");
                        }
                    } catch (Exception InputMismatchException) {
                        scanner=new Scanner(System.in); // Reinitiate the scanner object or use scanner.nextLine() to read bad input.
                        System.out.print("Wrong input!\nChoose again:");
                    }
    

    【讨论】:

    • 这对我来说是新知识。我不知道它是这样工作的。非常感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多