hasNextInt()的while循环完成,但是程序在执行完之后什么也不做 [英] while loop with hasNextInt() finishes, but program does not do anything after it

查看:46
本文介绍了hasNextInt()的while循环完成,但是程序在执行完之后什么也不做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在这里有这个程序:

So I have this program here:

ArrayList<Integer> meh = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
System.out.print("Input 3 numbers: ");

while (sc.hasNextInt()) {
    meh.add(sc.nextInt());
    System.out.println("meeeeeep");
}

System.out.println("Goodbye");

输出(如果输入了3个整数):

Output (if 3 integers are inputed):

meeeeeep
meeeeeep
meeeeeep

它不会打印再见消息,也不会执行我在消息之后所做的任何事情.

It doesn't print the goodbye message, or do anything that I put after it.

推荐答案

这是因为扫描程序正在等待即将到来的输入. sc.hasNextInt()正在等待下一个标记,并确定它是否为整数.

That's because the scanner is waiting for the coming input. sc.hasNextInt() is waiting for the next token and to determine if it is a int.

要解决此问题,请尝试按行阅读并使用 String.split();

To solve this, try reading by line and split on " " using String.split();

另一种解决方案可能是在for循环中执行此操作:

Another solution might be to do this in a for loop:

for (int i = 0; i < 3; ++i) {
    meh.add(sc.nextInt());
    System.out.println("meeeeeep");
}

这篇关于hasNextInt()的while循环完成,但是程序在执行完之后什么也不做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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