package com.exception_;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputInteger {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 0;
while (true) {
try {
System.out.print("输入一个整数:");
//若抛出异常,则在执行该语句后直接进入catch,接下来的语句不会执行
num = scanner.nextInt();
//如果运行无异常,则执行break
break;
} catch (Exception e) {
System.out.println("输入的不是整数,请重新输入!");
scanner = new Scanner(System.in);
}
}
System.out.println("输入的整数为" + num);
}
}
上面代码catch中的num=Scanner.nextInt() 如果不写,会导致该段代码陷入无限循环:
查阅相关资料后,陷入死循环的大概原因如下:
当输入非整型数时,系统会抛出 InputMismatchException 异常时不会清除键盘缓冲区中的字符串,因此循环调用nextInt()时,仍然能够读取到上次输入的字符串,导致陷入死循环,使用新对象,会"清空"缓冲? 而使用next() + Integer.parseInt() 则不会产生此问题。