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

Java中try-catch与while循环结合为何触发无限循环?

石头剪刀布游戏输入验证的无限循环问题

当输入非整数时程序陷入无限循环的核心原因是:Scanner的输入缓冲区里残留了无效的非整数内容。

当你输入字母、符号这类非整数内容时,sc.nextInt()无法解析,会直接抛出异常,但这些无效内容并没有被从输入缓冲区中清除。下一轮循环执行sc.nextInt()时,它会直接读取缓冲区里的旧无效内容,再次抛出异常,循环往复就形成了无限循环,根本不会等待新的输入。

修正后的代码

只需要在catch块中调用sc.next(),把缓冲区里的无效内容消费掉,就能让Scanner在下一次循环时接收新的输入:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int number;

        while (true) {
            System.out.print("Enter a number : ");
            try {
                number = sc.nextInt();
                break;
            } catch (Exception e) {
                System.out.println("Invalid Input");
                // 消费掉缓冲区里的无效输入
                sc.next();
            }
        }

        System.out.println(number);
    }
}

你也可以用sc.nextLine()替代sc.next(),不过在当前的循环场景下,sc.next()已经能处理单段的无效输入;如果后续有复杂输入场景,使用sc.nextLine()时需要注意处理可能残留的换行符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:25:17