I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args){
number();
}
public static int number() {
System.out.print("Enter a number: ");
Scanner readLine = new Scanner(System.in);
boolean isInteger = false;
while (!isInteger) {
try {
int numbers = readLine.nextInt();
System.out.println(numbers);
isInteger = true;
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error :" + e.getMessage());
}
}
return 0;
}
}