Java中输入触发异常时代码为何无限循环且不等待新输入?
Java输入校验死循环问题排查与修复
问题原因
- 当
Scanner的nextInt()方法触发InputMismatchException时,不会主动读取缓冲区中不符合int格式的错误输入,这段内容会一直残留在输入缓冲区中 - 下一轮循环再次调用
nextInt()时,仍然会读取到这段残留的非法内容,重复抛出异常,导致程序无限打印提示语,不会等待新的用户输入 - 附加问题:当前代码没有输入前的提示,用户不知道需要输入内容,且判断逻辑未排除0值(0不属于正整数)
修复方法
- 在
catch代码块中新增in.nextLine()调用,主动清空输入缓冲区的残留非法内容 - 输入前增加用户提示,优化交互体验
- 调整负数判断条件为
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
相关产品推荐
相关产品推荐

