What's an easy way to force users to input a positive integer when prompted?
I'm in Java 1 in Uni right now, and this has been bugging me. We have learned about the scanner look ahead methods, and the general practice until today was to use
Scanner console = new Scanner(System.in);
while (!console.hasNextInt() ) {
*prompt user to reenter an integer*
}
int x = console.nextInt();
This was fine when I just needed an integer, but today we did an exercise where we needed the user to input a positive integer and I couldn't figure out a good way to force them to do this. I tried to have two conditions in the while loop
while( !console.hasNextInt() || console.nextInt() < 0 ) {
*prompt user to enter positive integer*
}
int x = console.nextInt();
But when I tried to compile it and run it, the code didn't work right. I would have to enter 3 numbers each time before the last one inputted would actually be assigned to x. I know that there has to be a better way to do this, and would appreciate any help with this. I have already turned in my assignment, not looking for help to finish it, just for future reference for myself.
Posted Feb 25, 2016, 1:53 AM UTC