Scanner.nextInt()与Scanner.nextLine()的异常处理 [英] Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()

查看:584
本文介绍了Scanner.nextInt()与Scanner.nextLine()的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题仅用于教育目的。我从Java教科书中拿下了下面的代码,好奇为什么在catch块中使用了input.nextLine()。

This question is solely for educational purposes. I took the following code from a textbook on Java and am curious why input.nextLine() is used in the catch block.

我试图用输入来编写程序。 nextInt()在它的位置。该程序将不再适当地捕获异常。当我传递一个除整数之外的值时,控制台会显示熟悉的线程中的异常错误消息。

I tried to write the program using input.nextInt() in its place. The program would no longer catch the exception properly. When I passed a value other than an integer, the console displayed the familiar "Exception in thread..." error message.

当我完全删除了一行代码时,控制台将无止境地运行catch块的System.out.println()表达式。

When I removed that line of code altogether, the console would endlessly run the catch block's System.out.println() expression.

Scanner.nextLine()的目的是什么?为什么每个这些场景都会出现不同的情况?

What is the purpose of Scanner.nextLine()? Why did each of these scenarios play out differently?

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()调用的目的是跳过垃圾编号...准备下次尝试让用户输入

When any of the nextXxx(...) methods fails, the scanner's input cursor is reset to where it was before the call. So the purpose of the nextLine() call in the exception handler is to skip over the "rubbish" number ... ready for the next attempt at getting the user to enter a number.

当您删除 nextLine()时,代码反复尝试重新分解相同的垃圾数字。

And when you removed the nextLine(), the code repeatedly attempted to reparse the same "rubbish" number.

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

It is also worth noting that if the nextInt() call succeeded, the scanner would be positioned immediately after the last character of the number. Assuming that you are interacting with the user via console input / output, it may be necessary or advisable to consume the rest of the line (up to the newline) by calling nextLine(). It depends what your application is going to do next.

这篇关于Scanner.nextInt()与Scanner.nextLine()的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆