【问题标题】:Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()Scanner.nextInt() 与 Scanner.nextLine() 的异常处理
【发布时间】: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


    【解决方案1】:

    当任何nextXxx(...) 方法失败时,扫描仪的输入光标将重置为调用之前的位置。因此,在异常处理程序中调用nextLine() 的目的是跳过“垃圾”数字……为下一次尝试让用户输入数字做好准备。

    当您删除 nextLine() 时,代码会反复尝试重新解析相同的“垃圾”号码。


    还值得注意的是,如果nextInt() 调用成功,扫描仪将立即定位在数字的最后一个字符之后。假设您通过控制台输入/输出与用户进行交互,可能通过调用 nextLine() 来消耗该行的其余部分(直到换行符)是必要的或可取的。这取决于您的应用程序接下来要做什么。

    【讨论】:

      猜你喜欢
      • 2012-07-12
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多