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

在Java do-while循环中使用try-catch时触发catch后循环意外退出问题

问题根本原因

  • 当Scanner的nextInt()方法因为输入非数字内容抛出InputMismatchException时,不会自动清空输入缓冲区里的非法内容。下一轮循环再调用nextInt()时,会直接读取缓冲区残留的非法内容,再次触发异常,反复进入catch块,看起来就像循环直接跳出了。
  • 额外隐患:你在判断输入数字超出1-3范围的分支里,又调用了一次nextInt(),这次调用没有被try-catch包裹,如果再次输入非数字内容会直接终止程序。

修复方案

需要做两处修改:

  1. 在catch块末尾调用keyboard.nextLine()清空输入缓冲区的残留内容,避免下一轮循环重复读取非法输入
  2. 移除范围校验分支里的第二次nextInt()调用,靠循环逻辑让用户重新输入即可,不需要重复读取

修复后完整代码如下:

private boolean madeChoice = false;
// 假设keyboard为已完成初始化的Scanner全局变量
public void whatToDo(){
    System.out.println("");
    System.out.println("");
    System.out.println("=====================================");
    System.out.println("Welcome");
    System.out.println("=====================================\n");
    System.out.println("What would you like to do today? Your choices are: \n");
    choices();

    do{
        try{
            System.out.println("");
            System.out.println("Please enter your choice");
            int numberEntered = keyboard.nextInt();

            if(numberEntered > 3 || numberEntered < 1){
                System.out.println("-----------------------------------------------------------");
                System.out.println("That is not a choice. Please choose from the following: \n");
                choices();
            }else{
                System.out.println("That is a good CHOICE");
                madeChoice = true;
            }
          
        }catch (InputMismatchException e){
            System.out.println("-----------------------------------------------------------");
            System.out.println("This is not a number. Please choose from the following: \n");
            choices();
            // 清空输入缓冲区的非法内容
            keyboard.nextLine();
        }

    }while(!madeChoice);

}

private void choices(){
    System.out.println("1. Add a new set into your account");
    System.out.println("2. See all the sets in your account");
    System.out.println("3. Exit the Account Manger.");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:24:00