我有一个 java 代码,我想从用户那里获取一个整数。如果该输入确实是一个整数,那么它接下来将通过控件进行扫描,但如果输入不是整数,则控件将再次进行扫描。问题是当用户给出的不是整数时,while 循环一次又一次地循环。比如,
public static void main(String[] args) { Scanner sc = new Scanner(System.in); boolean isValid = true; while (isValid) { try{ System.out.print("Please enter any int:"); int a = sc.nextInt(); isValid = false; }catch(Exception e){ System.out.println("ERROR : Didn't enter any int"); } } System.out.println("System running..."); }
若用户输入a则会导致
Please enter any int:ERROR : Didn't enter any int
Please enter any int:ERROR : Didn't enter any int
Please enter any int:ERROR : Didn't enter any int
Please enter any int:ERROR : Didn't enter any int
Please enter any int:ERROR : Didn't enter any int
...........
中,若用户输入字符串或其他非整型数据,此时程序会进入死循环,导致这样的原因为Scanner对象sc的缓存并未清理此时须将对象缓存清理释放。
可使用对象功能清理缓存区,如
sc.next();
此时代码块结构为
public static void main(String[] args) { Scanner sc = new Scanner(System.in); boolean isValid = true; while (isValid) { try{ System.out.print("Please enter any int:"); int a = sc.nextInt(); isValid = false; }catch(Exception e){ System.out.println("ERROR : Didn't enter any int"); sc.next(); //清理缓存区防止死循环 } } System.out.println("System running..."); }