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?
} while (console.hasNextInt());can return true/false only if there is data inSystem.inwhich can be evaluated. But when you are usingnextInt()in first iteration you are consuming provided value and there is nothing left forhasNextIntto 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