Java如何实现输入错误时循环提示直至用户输入合法Integer整数?
实现代码
你需要在外层添加循环控制重新输入逻辑,同时每次检测到非法输入后清空Scanner的输入缓存,避免重复读取同一段错误内容导致死循环。修改后的完整代码如下:
import java.util.Scanner; public class Loop{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); // 无限循环,仅当输入合法整数时退出 while (true) { System.out.println("Enter an Integer: "); if (scan.hasNextInt()) { int index = scan.nextInt(); scan.nextLine(); System.out.println("Index = " + index); // 输入合法,终止循环 break; } else if (scan.hasNextDouble()) { System.out.println("Error: Index is Double not Integer."); } else { System.out.println("Error: Index is not Integer."); } // 清空本次非法输入的缓存内容 scan.nextLine(); } // 释放Scanner资源 scan.close(); } }
核心逻辑说明
- 外层使用
while(true)实现无限循环,只有用户输入合法整数时才执行break跳出循环,满足重复输入要求 - 所有非法输入判定分支结束后,必须调用
scan.nextLine()清空Scanner缓冲区,否则Scanner会一直读取同一段非法输入,陷入死循环 - 代码中把变量名
Index修改为index,符合Java变量首字母小写的命名规范 - 最后新增
scan.close()释放IO资源,符合编码规范
内容的提问来源于stack exchange,提问作者L. Jacob
相关产品推荐
相关产品推荐

