如何在while循环中使用.nextInt()和hasNextInt() [英] How to use .nextInt() and hasNextInt() in a while loop

查看:302
本文介绍了如何在while循环中使用.nextInt()和hasNextInt()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

1 1 2

然后它应该分别读取每个整数并以新行打印。程序必须读取的整数数量不是事先给出的,所以我要做的是使用while循环,在没有更多的整数读取之后结束。这是我写的代码:

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 (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?

推荐答案

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

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.

如果您不熟悉从文件中读取,请创建一个项目文件夹中的test.txt 并使用扫描程序扫描=新扫描程序(新文件(test.txt)); 和您的代码。

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

这篇关于如何在while循环中使用.nextInt()和hasNextInt()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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