Vedant Daga
Vedant Daga

Reputation: 11

Java Scanner for ArrayList data

I'm trying to use a do-while loop to get information for an ArrayList, but I get this output:

Please input your number (type a letter to finish): 2

3

Please input your number (type a letter to finish): 4

Please input your number (type a letter to finish): q

But the operation succeeds and ArrayList contains all three numbers (2, 3, 4) as expected even without the prompt having been printed for one of them

    do {
        num = getNumber("Please input your number (type a letter to finish): ");
        data.add(num);
    } while (console.hasNextInt());

and the method getNumber:

public static int getNumber(String prompt) {
    System.out.print(prompt);
    return console.nextInt();
}

How to I get it to print the prompt for all numbers?

Upvotes: 1

Views: 133

Answers (1)

River
River

Reputation: 9093

Your main problem is calling nextInt() before hasNextInt().

You need to do it the other way around.

Normally, nextInt() simply consumes the data waited for using hasNextInt(), but if no data has been recieved in this way, nextInt() will itself block. This is what is causing your problem.

Look at the control flow of your program:

  1. getNumber is called
  2. prompt is printed
  3. nextInt() blocks for input
  4. input is given and getNumber returns
  5. in the do-while loop, hasNextInt() blocks for input

    Here is the problem, your program waits for input again but no new prompt has had a chance to be printed!

  6. In the next iteration, nextInt() simply consumes the int waited for in step 5
  7. Now the usual pattern of hasNextInt() before nextInt() has been restored, and so your program behaves as expected from this point on

Upvotes: 1

Related Questions