java nextLine()是如何丢弃这段代码中的输入的?

pokxtpni  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(162)

如果我从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]);
}
}
lp0sw83n

lp0sw83n1#

因为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"); 
}

相关问题