What's the best way about getting a valid integer from a user that is in a specified range (0,20) and is an int
. If they enter an invalid integer print out error.
I am thinking something like:
int choice = -1;
while(!scanner.hasNextInt() || choice < 0 || choice > 20) {
System.out.println("Error");
scanner.next(); //clear the buffer
}
choice = scanner.nextInt();
Is this correct or is there a better way?
Where do you change choice inside of your while loop? If it's not changed you can't expect to use it in your if block's boolean condition.
You'll have to check that the Scanner doesn't have an int and if it does have an int, get choice and check that separately.
Pseudocode:
You can do something like this:
This program will keep asking for an input until it gets a valid one.
Make sure you understand every step of the program..