New programmer here. This is probably a really basic question, but it\'s stumping me nevertheless.
What I\'m trying to do is write a method that supplies only one in
//while (test == false) { // Line #1
while (!test) { /* Better notation */ // Line #2
System.out.println("Integers only please"); // Line #3
test = input.hasNextInt(); // Line #4
} // Line #5
The problem is that in line #4 above, input.hasNextInt()
only tests if an integer is inputted, and does not ask for a new integer. If the user inputs something other than an integer, hasNextInt()
returns false
and you cannot ask for nextInt()
, because then an InputMismatchException
is thrown, since the Scanner
is still expecting an integer.
You must use next()
instead of nextInt()
:
while (!input.hasNextInt()) {
input.next();
// That will 'consume' the result, but doesn't use it.
}
int result = input.nextInt();
input.close();
return result;