input.nextInt()如何正常工作?

这是该计划

public class bInputMismathcExceptionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean continueInput = true; do { try { System.out.println("Enter an integer:"); int num = input.nextInt(); System.out.println("the number is " + num); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (Incorrect input: an integer is required)"); } input.nextLine(); } while (continueInput); } } 

我知道nextInt()只读取整数而不是"\n" ,但为什么我们需要input.nextLine()来读取"\n" ? 有必要吗?? 因为我认为即使没有input.nextLine() ,在它返回try {}input.nextInt()仍然可以读取我输入的下一个整数,但实际上它是一个无限循环。

我仍然不知道它背后的逻辑,希望有人能帮助我。

这里有必要的原因是因为输入失败时会发生什么。

例如,尝试删除input.nextLine()部分,再次运行程序,当它要求输入时,输入abc并按Return

结果将是无限循环。 为什么?

因为nextInt()会尝试读取传入的输入。 它将看到此输入不是整数,并将抛出exception。 但是,输入未清除。 它仍然是缓冲区中的abc 。 因此,回到循环将导致它尝试一遍又一遍地解析相同的abc

使用nextLine()将清除缓冲区,以便在错误之后读取的下一个输入将是您输入的坏行之后的新输入。

但为什么我们需要input.nextLine()来读取“\ n”? 有必要吗??

是的(实际上这很常见),否则你将如何消耗剩余的\n ? 如果您不想使用nextLine来使用左\n ,请使用其他扫描程序对象(我建议这样 ):

 Scanner input1 = new Scanner(System.in); Scanner input2 = new Scanner(System.in); input1.nextInt(); input2.nextLine(); 

或者使用nextLine读取整数值并稍后将其转换为int这样您以后就不必使用新的行字符。