nextLine() 如何丢弃此代码中的输入?

How is nextLine() discarding input in this code?

如果我从 catch 块中删除 input.nextLine() ,则会开始无限循环。评论说 input.nextLine() 正在丢弃输入。它到底是怎么做到的?

import java.util.*;

public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;

do {
  try {
    System.out.print("Enter an integer: ");
    int number = input.nextInt();

    // Display the result
    System.out.println(
      "The number entered is " + number);

    continueInput = false;
  } 
  catch (InputMismatchException ex) {
    System.out.println("Try again. (" + 
      "Incorrect input: an integer is required)");
    input.nextLine(); // discard input 
  }
} while (continueInput);
}
}

还有一件事.. 另一方面,下面列出的代码在不包含任何 input.nextLine() 语句的情况下也能完美运行。为什么?

import java.util.*;

public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter four inputs::");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int[] x = {a,b,c,d};
for(int i = 0; i<x.length; i++)
    System.out.println(x[i]);
}
}

因为 input.nextInt(); 只会消耗一个 int,所以在 catch 块的缓冲区中仍然有未决字符(不是 int)。如果您不使用 nextLine() 读取它们,那么您会进入一个无限循环,因为它会检查 int,没有找到,抛出 Exception,然后检查 int.

你可以

catch (InputMismatchException ex) {
    System.out.println("Try again. (" + 
      "Incorrect input: an integer is required) " +
      input.nextLine() + " is not an int"); 
}