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

查看:24
本文介绍了如何在 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 并使用 Scanner scan = new Scanner(new File("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天全站免登陆