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

Java Scanner第二次读取整数输入问题:判断输入为'end'或数字

问题分析与解决

你的代码核心问题是重复读取输入流:
调用scan.next()判断是否为"end"时,已经读取了一个输入值。如果这个输入不是"end",后续的scan.hasNextInt()和scan.nextInt()会读取下一个新输入,导致第一次输入的数字被直接跳过,必须第二次输入才能被处理。

修正后的代码示例

Scanner scan = new Scanner(System.in);
boolean play = true;

while (play) {
    int answer = ask(); // 假设ask()是你实现的生成目标数字的方法
    String input = scan.next(); // 一次性读取输入并存储

    if (input.equals("end")) {
        System.out.println("ended");
        play = false;
    } else {
        try {
            int number = Integer.parseInt(input);
            if (number == answer) {
                // 匹配成功的逻辑,示例:
                System.out.println("答对了!");
            } else {
                // 匹配失败的逻辑,示例:
                System.out.println("答错了,再试试?");
            }
        } catch (NumberFormatException e) {
            // 处理既不是"end"也不是整数的无效输入
            System.out.println("输入无效,请输入数字或'end'结束游戏");
        }
    }
}
scan.close();

关键修正点

  • 只调用一次scan.next()读取输入,将结果存入字符串变量,避免多次读取输入流导致的输入丢失
  • 使用Integer.parseInt()配合try-catch,统一处理输入转整数的逻辑,同时覆盖非数字非"end"的无效输入场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:52:35