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

标签 java java.util.scanner

如果我从 catch block 中删除 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,所以缓冲区中仍然有待处理的字符(不是 int >) 在 catch block 中。如果您不使用 nextLine() 读取它们,则会进入无限循环,因为它会检查 int,如果找不到,则会抛出 Exception ,然后检查 int

你可以做

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

关于java - nextLine() 如何丢弃此代码中的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127201/

相关文章:

java - 从列表中的对象获取原始类

java - Mozilla犀牛 : Default JavaScript Compliance Level

java - For 循环中的多个扫描仪输入

java - 如何将 .txt 文件中的 double 读入 ArrayList

java - 如何使用扫描仪作为控制台输入来捕获回车键?

java - 使用 NativeModules 时在 native react 中出现 "must be caught or declared to be thrown"

java - 通过子面板中 JButton 的 ActionEvent 将组件添加到父容器

java - 如何在 Lucene 3.0.1 中索引 BigDecimal 值

java - 使用扫描仪扫描字数和行数 (Java)

java - 为什么在调用 nextLine() 方法时不能在 Scanner(System.in) 中输入字符串?