The InputMismatchException
is raised by the method nextInt
of a Scanner instance after it reads any character which is not the integer. The maximum and minimum size of integer variable (int
) in Java also must be taken under consideration.
The question is a bit unclear, but from the given code and sample user input I'm guessing that the goal to make user re-enter a numerical value until the required number is typed while informing user about the wrong input type.
Here's the way it could be achieved:
public class NumberGuessing {
public static void main(String[] args) {
int guess = -1;
int num = 9;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Guess a number between 1 and 10.");
String enteredValue = scan.next();
while(!validNumber(enteredValue)) {
System.out.println("Enter a valid number.");
enteredValue = scan.next();
}
guess = Integer.parseInt(enteredValue);
if (guess == num) {
System.out.println("That's right! The hidden number was: " + num);
break;
}
}
}
private static boolean validNumber(String s) {
try{
int num = Integer.parseInt(s);
return num >= 1 && num <= 10; //change this to `return true;` if range check is not needed
}catch(NumberFormatException e) {
return false;
}
}
}
The reason it uses the method next()
of a Scanner instance is that the nextInt
reads only the first string it sees without reading the new line character. So when looping with the nextInt
inside, the next iteration would try to read new line character which would also result in InputMismatchException
.
It's better to read whole line with next()
from a console and later parse it aligning the input to user needs.
Edit2: If the range check is not needed you could just go with regex check:
while (guess != num) {
System.out.println("Guess a number between 1 and 10.");
String enteredValue = scan.next();
while (!enteredValue.matches("-?\\d+")) {
System.out.println("Enter a valid number.");
enteredValue = scan.next();
}
guess = Integer.parseInt(enteredValue);
}
It allows the leading '0' in numbers which in some cases might not be valid number, if you want to avoid leading '0' change the matches
method to .matches("-?(0|[1-9]\\d*)")
.