user1042623
user1042623

Reputation: 1

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

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.

Upvotes: 0

Views: 821

Answers (1)

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

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

Upvotes: 4

Related Questions