I haven't coded in a few years and have been writing simple Java programs to re-familiarize myself with basic principles. However, I'm having trouble getting my do-while loop to act how I want it to. I guess I'm not understanding exactly how do-while loops work, but what I want is to gather user input from System.in as an int, and continue to ask for a valid int input if they enter some other data form. What I have is:
do {
System.out.print("Input: ");
userOption = userInput.nextInt();
} while (!userInput.hasNextInt());
System.out.println("You chose to: " + menuItems.get((userOption - 1)));
This doesn't work for two reasons. First, if I enter a non-int value, it immediately crashes throwing an input mismatch exception. Second, if I do enter a valid int, I always have to enter it twice. I.E., the console will ask for "Input: ", I'll enter say "2", the console will advance to the next line and wait for another input (but without printing anything), and then when I enter a second int it outputs the "You chose to [...]".
I have tried over a dozen different variations that just keep getting more complex, while loops inside do-while, inside if-else, but I'm sure I'm over complicating matters and am missing a simple concept. Any help is very much appreciated!
hasNextIntbefore reading theintand store the value in a boolean variable.