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

如何解决Java猜数字游戏catch异常后循环消耗尝试次数不返回Scanner输入的问题

问题根因
  • Scanner.nextInt()在遇到非数字输入抛出异常时,不会主动清空输入缓冲区里的错误内容,该内容会一直残留,导致下一次循环调用nextInt()时重复读取到相同的错误内容,持续触发异常。
  • 现有for循环的计数变量无论本次输入是否有效都会自动累加,无效输入同样会占用尝试次数,直接耗尽20次配额。
修复方案

需要做两处核心调整:

  1. 捕获输入异常后,调用Scanner.nextLine()清空输入缓冲区的残留错误内容
  2. 无效输入(输入异常、超出1-50范围)时不增加尝试次数,避免占用配额

修改后的完整代码如下:

import java.util.*;

public class GuessingGame {
    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        // 生成1-50的随机正确数字
        int correctNum = 1 + (int)(50 * Math.random());
        int maxAttempts = 20;  
        int usedAttempts = 0;
        System.out.println("请输入1-50之间的数字进行猜测:");
        
        while (usedAttempts < maxAttempts) {            
            try {
                int inputNum = sc.nextInt();
                // 仅输入为合法数字时才消耗尝试次数
                usedAttempts++;

                if (inputNum == correctNum) {
                    System.out.println("恭喜你猜对了,共尝试了"+ usedAttempts + "次。");
                    break;
                } else if (inputNum > 50 || inputNum < 1) {
                    System.err.println("输入超出范围,请重新输入1-50之间的数字:");
                    // 范围违规不消耗次数,回退计数
                    usedAttempts--;
                } else if(inputNum < correctNum) {
                    System.out.println("猜的数字太小了,再试试。");
                } else {
                    System.out.println("猜的数字太大了,再试试。");
                }
            } catch(Exception e) {
                System.err.println("输入无效,请输入合法数字:");
                // 清空缓冲区残留的错误输入,避免下一轮循环重复读取报错
                sc.nextLine();
            }
        }

        // 次数耗尽未猜对的提示
        if (usedAttempts >= maxAttempts) {
            System.out.println("很遗憾,你已经用完了"+maxAttempts+"次机会,正确数字是:"+correctNum);
        }
        sc.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:09:04