If you are using scanner, you can use the nextInt()
method with the condition hasNextInt()
which would only read integer inputs. Have a look at this post for example:
Taken from the above mentioned post.
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
Also you can look at the documentation for scanner’s nextInt()
here
solved How to handle wrong user input [closed]