You can take it in as a string, and then use regex to test if the string contains only numbers. So, only assign num
the integer value of the string if it is in fact an integer number. That means you need to initialize num
to -1
so that if it is not an integer, the while condition will be true and it will start over.
Scanner scnr = new Scanner(System.in);
int num = -1;
String s;
do {
System.out.println("Enter a number (int): ");
s = scnr.next().trim(); // trim so that numbers with whitespace are valid
if (s.matches("\\d+")) { // if the string contains only numbers 0-9
num = Integer.parseInt(s);
}
} while(num < 0 || !scnr.hasNextLine());
Sample run:
Enter a number (int):
-5
Enter a number (int):
fdshgdf
Enter a number (int):
5.5
Enter a number (int):
5