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
You were close: this works fine for me:
Scanner input = new Scanner(System.in); //construct scanner
while(!input.hasNextInt()) {
input.next(); // next input is not an int, so consume it and move on
}
int finalInput = input.nextInt();
input.close(); //closing scanner
System.out.println("finalInput: " + finalInput);
By calling input.next()
in your while loop, you consume the non-integer content and try again, and again, until the next input is an int.
//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;