I am writing a command line program and would like to make the the user to enters a valid age (integer). By using the Scanner class, I have something like this:
int getAge() {
Scanner = new Scanner(System.in);
int age;
boolean isValid = false;
while(!isValid) {
System.out.println("Please enter your age");
if (myScanner.hasNext()) {
if (myScanner.hasNextInt()) {
age = myScanner.nextInt();
isValid = true;
} else {
System.out.println("Please enter an integer");
}
}
}
return age;
}
The problem being that while in the loop it keeps reading input without waiting for a new value. How can I get around this?
You are not reading any token in your
elsepath thus processing the same input over and over again. Just add the following lineinside the
else-block.