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
相关产品推荐
相关产品推荐

