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

时间:2015-06-29 23:29:24

标签: java java.util.scanner next

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

1 个答案:

答案 0 :(得分:2)

由于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"); }

你可以做到

HibernateUtil