【发布时间】:2014-08-13 02:49:37
【问题描述】:
此问题仅用于教育目的。我从一本关于 Java 的教科书中获取了以下代码,我很好奇为什么在 catch 块中使用 input.nextLine()。
我尝试使用 input.nextInt() 来编写程序。该程序将不再正确捕获异常。当我传递一个不是整数的值时,控制台会显示熟悉的“线程中的异常...”错误消息。
当我完全删除那行代码时,控制台将无休止地运行 catch 块的 System.out.println() 表达式。
Scanner.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();
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();
}
}
while (continueInput);
}
}
谢谢大家
【问题讨论】:
标签: java exception-handling java.util.scanner