1

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?

Community
  • 1
  • 1
  • `} while (console.hasNextInt());` can return true/false only if there is data in `System.in` which can be evaluated. But when you are using `nextInt()` in first iteration you are consuming provided value and there is nothing left for `hasNextInt` to test so it need to wait for new value. Another problem is that you are testing if user provided proper number after already reading it first time (since condition is tested after first iteration). Maybe you are looking for something like: [How to handle infinite loop caused by invalid input using Scanner](http://stackoverflow.com/q/3572160) – Pshemo Mar 10 '17 at 20:22

1 Answers1

1

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
Community
  • 1
  • 1
River
  • 7,472
  • 11
  • 47
  • 61