Reputation: 11
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
Reputation: 9093
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:
getNumber
is calledprompt
is printednextInt()
blocks for inputgetNumber
returnsin 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!
nextInt()
simply consumes the int
waited for in step 5hasNextInt()
before nextInt()
has been restored, and so your program behaves as expected from this point onUpvotes: 1