You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用try catch做输入校验时捕获异常后如何继续请求用户输入

问题原因
  • 你的try-catch块包裹在整个菜单循环外层,一旦触发InputMismatchException就会直接跳出循环,执行完异常提示后方法直接结束,自然无法重新触发输入逻辑。
  • Scanner接收到非整数输入时,错误内容不会被自动消费,会一直残留在输入缓冲区中,如果不手动清理,后续的输入读取操作会持续触发异常。
修复思路

将输入合法性校验(整数校验+范围校验)收拢到输入获取的逻辑内部,循环请求输入直到拿到符合要求的值再返回主流程执行菜单逻辑,同时每次捕获输入不匹配异常后清理缓冲区残留的错误内容。

实现代码

首先修改getUserSelectionFromMenu方法,在校验通过前不会返回结果:

private int getUserSelectionFromMenu() {
    Scanner scanner = new Scanner(System.in);
    int input = 0;
    while (true) {
        try {
            input = scanner.nextInt();
            if (input >=1 && input <=7) {
                return input;
            }
            System.out.println("Please enter an option between 1-7!\n");
            // 清理缓冲区剩余的换行符,避免影响后续读取
            scanner.nextLine();
        } catch (InputMismatchException e) {
            System.out.println("Please enter an integer number !");
            // 清理缓冲区残留的错误输入
            scanner.nextLine();
        }
    }
}

调整后的SystemExecute方法可以移除外层的异常捕获,逻辑更简洁:

public void SystemExecute() {
    System.out.println("Welcome to our project!");
    int userSelection = 0;
    Boolean incremental;

    while (userSelection != 6) {
        printMenu();
        // 此处拿到的一定是1-7区间的合法整数
        userSelection = getUserSelectionFromMenu();

        switch (userSelection) {
            case 1: {
                loadFile();
                break;
            }
            case 2: {
                printGraphInformation();
                break;
            }
            case 3: {
                printTargetInformation();
                break;
            }
            case 4: {
                printTargetConnectionStatus();
                break;
            }
            case 5: {
                incremental = askForIncremental();
                try {
                    TaskExecuting.executeTask(graph, incremental, graphSummary);
                } catch (OpeningFileCrash | FileNotFound e) {
                    System.out.println(e.getMessage());
                }
                firstRun = false;
                break;
            }
            case 6: {
                exitFromSystem();
                break;
            }
            case 7: {
                saveSystemStatus();
                break;
            }
            default: {
                System.out.println("Please enter an option between 1-7!\n");
                break;
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Linki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:45:06