如果我从 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/