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

Java Scanner如何防止回车键刷屏引发的输入验证异常

修复方案

你的代码出现连续错误提示挤在一起的问题,核心原因是内部循环使用System.out.print()输出提示(无换行),且连续回车产生的空行被多次判定为无效输入,导致多次提示在同一行堆叠。

在不修改输入读取方式、保留原有函数结构的前提下,只需做一处小调整:

将内部循环里的System.out.print()改为System.out.println(),让每个错误提示单独占一行。

修改后的代码:

public int UserChoiceValidate() {
    Scanner sc = new Scanner(System.in);
    int choice;
    do {
        System.out.print("Please enter your choice: ");
        while (!sc.hasNextInt()) {
            // 改为println,确保每个错误提示单独换行
            System.out.println("Input invalid, please retry: ");
            sc.nextLine(); // 消费无效输入行
        }
        choice = sc.nextInt();
        if (choice <= 0 || choice > 5) {
            System.out.println("Choice not included, please retry");
        }
    } while (choice <= 0 || choice > 5);
    return choice;
}

修改后,连续回车产生的无效输入会输出独立的错误提示行,不会再出现堆叠的情况。该改动完全保留原函数结构和int类型读取逻辑,直接复制修改点到其他同结构函数即可,无需大规模重构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:45:39