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

Java中输入触发异常时代码为何无限循环且不等待新输入?

Java输入校验死循环问题排查与修复

问题原因

  • 当Scanner的nextInt()方法触发InputMismatchException时,不会主动读取缓冲区中不符合int格式的错误输入,这段内容会一直残留在输入缓冲区中
  • 下一轮循环再次调用nextInt()时,仍然会读取到这段残留的非法内容,重复抛出异常,导致程序无限打印提示语,不会等待新的用户输入
  • 附加问题:当前代码没有输入前的提示,用户不知道需要输入内容,且判断逻辑未排除0值(0不属于正整数)

修复方法

  1. 在catch代码块中新增in.nextLine()调用,主动清空输入缓冲区的残留非法内容
  2. 输入前增加用户提示,优化交互体验
  3. 调整负数判断条件为x <= 0,符合正整数的校验要求

修正后的代码

int x = 0;
boolean inputValid = false;
Scanner in = new Scanner(System.in);
        
while (!inputValid) {
    System.out.print("请输入正整数:");
    try {
        x = in.nextInt();
        // 校验是否为正整数
        if (x <= 0) {
            System.out.println("Please enter a positive integer.");
        } else {
            inputValid = true;
        }
    } catch (InputMismatchException e) {
        System.out.println("Please enter a positive integer.");
        // 清空缓冲区残留的非法输入
        in.nextLine();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:21:03