繁体   English   中英

使用Scanner.nextInt()与Scanner.nextLine()进行异常处理

[英]Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()

这个问题仅出于教育目的。 我从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);
    }   
}

感谢大家

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

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM