Java 如何在 while 循环中使用 .nextInt() 和 hasNextInt()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26566773/
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 02:49:43  来源:igfitidea点击:

How to use .nextInt() and hasNextInt() in a while loop

javainputwhile-loopjava.util.scanner

提问by patriciasmh

So I want my program to read an input, which has some integers in one line, for example:

所以我希望我的程序读取一个输入,它在一行中有一些整数,例如:

1 1 2

1 1 2

Then it should read every integer separately and print it in a new line. The number of integers the program has to read is not given in advance, so what I am trying to do is use a while loop, which ends after there are no more integers to read. This is the code I wrote:

然后它应该分别读取每个整数并将其打印在新行中。程序必须读取的整数数量没有预先给出,所以我试图做的是使用一个 while 循环,它在没有更多的整数可供读取后结束。这是我写的代码:

while (scan.hasNextInt()) {
    int x = scan.nextInt();
    System.out.println(x);
}

but it's not working correctly, because the loop never ends, it just wants the user to input more integers. What am I missing here?

但它不能正常工作,因为循环永远不会结束,它只是希望用户输入更多的整数。我在这里缺少什么?

采纳答案by Gooey

Your scanner basically waits until an end of file comes in. And if you use it in the console that does not happen, so it will continue to run. Try reading the integers from a file, you will notice your program will terminate.

您的扫描仪基本上会等到文件结束。如果您在控制台中使用它,则不会发生,因此它将继续运行。尝试从文件中读取整数,您会注意到您的程序将终止。

In case you are new to reading from a file, create a test.txtin your project folder and use Scanner scan = new Scanner(new File("test.txt"));with your code.

如果您不熟悉读取文件,请test.txt在您的项目文件夹中创建一个并Scanner scan = new Scanner(new File("test.txt"));与您的代码一起使用。

回答by user2864740

The hasNextIntcall blocksuntil it has enough information to make the decision of "yes/no".

hasNextInt调用,直到它有足够的信息来做出的“是/否”的决定。

Press Ctrl+Z on Windows (or Ctrl+D on "unix")to close the standard input streamand trigger an EOF. Alternatively, type in a non-integer and press enter.

在 Windows 上Ctrl+Z(或在“unix”上按 Ctrl+D)关闭标准输入流并触发EOF。或者,输入一个非整数并按回车键

Console input is normally line-buffered: enter must be pressed (or EOF triggered) and the entire line will be processed at once.

控制台输入通常是行缓冲的:必须按下回车(或触发 EOF),整行将被立即处理

Examples, where ^Z means Ctrl+Z (or Ctrl+D):

示例,其中 ^Z 表示 Ctrl+Z(或 Ctrl+D):

1 2 3<enter>4 5 6^Z   -- read in 6 integers and end because stream closed
                      -- (two lines are processed: after <enter>, after ^Z)
1 2 3 foo 4<enter>    -- read in 3 integers and end because non-integer found
                      -- (one line is processed: after <enter>)


See also:

也可以看看:

回答by Cfx

If you like to stop your loop after the line, create your Scannerlike this:

如果您想在该行之后停止循环,请Scanner像这样创建:

public static void main(final String[] args) {
    Scanner scan = new Scanner(System.in).useDelimiter(" *");
    while (scan.hasNextInt() && scan.hasNext()) {
        int x = scan.nextInt();
        System.out.println(x);
    }

}

The trick is to define a delimiter that contains whitespace, the empty expression, but not the next line character. This way the Scannersees the \nfollowed by a delimiter (nothing) and the input stops after pressing return.

诀窍是定义一个包含空格、空表达式但不包含下一行字符的分隔符。这样就Scanner可以看到\n后面跟着一个分隔符(没有)并且在按下回车后输入停止。

Example: 1 2 3\n will give the following tokens: Integer(1), Integer(2), Integer(3), Noninteger(\n) Thus the hasNextIntreturns false.

示例: 1 2 3\n 将给出以下标记: Integer(1), Integer(2), Integer(3), Noninteger(\n) 因此hasNextInt返回false。