I defined a function readInt()
which returns an int
(based on Scanner.nextInt()
).
The problem is: if I enter a character, I get this exception: (java.util.InputMismatchException
).
I've tried to fix it without success using a try-catch
block.
What's wrong?
public static int readInt(String message, int min, int max)
{
displayBlack(message);
int number = scanner.nextInt();
try{
if (number < min || number > max)
{
return readInt("Erreur, Selectionner un nombre entre " + min + " et " + max, min, max);
} else
{
return number;
}
}
catch (NumberFormatException e){
return readInt(message, min, max);
}
}
EDIT :
I changed my function to :
public static int readInt(String message, int min, int max)
{
displayBlack(message);
try{
String result = scanner.next();
int number = Integer.parseInt(result);
if (number < min || number > max)
{
return readInt("Erreur, Selectionner un nombre entre " + min + " et " + max, min, max);
} else
{
return number;
}
}
catch (Exception e){
return readInt("Erreur, Selectionner un nombre entre " + min + " et " + max, min, max);
}
}
Now it's working. Is it a good way or a dirty hack?