Im trying to check whether the input from the User is an int or not.
Heres my code so far:
static int readInt(Scanner userInput) {
int intValue = 0;
try {
System.out.print("Please enter a number:");
intValue = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
Input.readInt(userInput);
}
return intValue;
}
The problem is: if I first give it input which is not a number and then after that i give it a number it always returns 0. If i give it a number the first attempt it returns the number I have given it.
What am I missing? Thanks in advance
edit: Im only allowed to use Integer.parseInt and Exceptions.
Input.readInt(userInput);to yourintValuewhile-loop to ensure that the program only continues forward when valid input has been received.