Java input.nextInt() 究竟是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28153886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:41:48  来源:igfitidea点击:

How does input.nextInt() work exactly?

java

提问by u4495367

This is the program

这是程序

public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean continueInput = true;
    do {
        try {
            System.out.println("Enter an integer:");
            int num = input.nextInt();

            System.out.println("the number is " + num);
            continueInput = false;
        }
        catch (InputMismatchException ex) {
            System.out.println("Try again. (Incorrect input: an integer is required)");
        } 
        input.nextLine();
    }   
    while (continueInput);

}
}

I know nextInt()only read the integer not the "\n", but why should we need the input.nextLine()to read the "\n"? is it necessary?? because I think even without input.nextLine(), after it goes back to try {}, the input.nextInt()can still read the next integer I type, but in fact it is a infinite loop.

我知道nextInt()只读取整数而不是"\n",但是为什么我们需要input.nextLine()读取"\n"?有必要吗??因为我认为即使没有input.nextLine(),回到 之后try {}input.nextInt()仍然可以读取我输入的下一个整数,但实际上它是一个无限循环。

I still don't know the logic behind it, hope someone can help me.

我仍然不知道它背后的逻辑,希望有人可以帮助我。

回答by Maroun

but why should we need the input.nextLine() to read the "\n"? is it necessary??

但是为什么我们需要 input.nextLine() 来读取“\n”?有必要吗??

Yes (actually it's very common to do that), otherwise how will you consume the remaining \n? If you don't want to use nextLineto consume the left \n, use a different scanner object (I don'trecommend this):

是的(实际上这样做很常见),否则你将如何消耗剩余的\n?如果您不想使用nextLineleft \n,请使用不同的扫描仪对象(我建议这样):

Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);

input1.nextInt();
input2.nextLine();

or use nextLineto read the integer value and convert it to intlater so you won't have to consume the new line character later.

或用于nextLine读取整数值并将其转换为int稍后,以便您以后不必使用换行符。

回答by RealSkeptic

The reason it is necessary here is because of what happens when the input fails.

这里有必要的原因是因为当输入失败时会发生什么。

For example, try removing the input.nextLine()part, run the program again, and when it asks for input, enter abcand press Return

例如,尝试移除input.nextLine()零件,再次运行程序,当它要求输入时,输入abc并按Return

The result will be an infinite loop. Why?

结果将是一个无限循环。为什么?

Because nextInt()will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abcin the buffer. So going back to the loop will cause it to try parsing the same abcover and over.

因为nextInt()会尝试读取传入的输入。它将看到此输入不是整数,并会抛出异常。但是,输入不会被清除。它仍将abc在缓冲区中。因此,返回循环将导致它abc一遍又一遍地尝试解析相同的内容。

Using nextLine()will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.

使用nextLine()将清除缓冲区,以便您在错误后读取的下一个输入将是您输入的错误行之后的新输入。