while loop with hasNextInt() finishes, but program does not do anything after it

安稳与你 提交于 2019-12-11 21:40:32

问题


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");

Output (if 3 integers are inputed):

meeeeeep
meeeeeep
meeeeeep

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


回答1:


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.

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

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");
}


来源:https://stackoverflow.com/questions/8101345/while-loop-with-hasnextint-finishes-but-program-does-not-do-anything-after-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!