You are stuck in the while loop because the index of your reader stays at the same point.
So if you type "some non numeric gibberish"
the pointer will stay at this point and the program will keep asking you to enter a number. You can solve this by either moving your index in the else clause:
Scanner reader = new Scanner(System.in);
boolean isANumberFlag = false;
int userX = 0;
do {
System.out.println("please enter a number: ");
if (reader.hasNextInt()) {
userX = reader.nextInt();
isANumberFlag = true;
}
else {
System.out.println("Please enter numbers only, try again: ");
reader.next(); //move your index in the else clause
}
}
while (isANumberFlag == false);
System.out.println(userX);
}
Note this solution will ask you to type something again if you type a word that is partial numeric, for instance: "notValid5000"
.
However if you type a partial numeric sentence, for instance: "notValid 5000"
it will say "Please enter numbers only, try again: "
and directly accept the numeric 5000
part, as an Integer.
Another solution is reading a line as a String and validating that the specific line is a int by using a regular expression:
Scanner reader = new Scanner(System.in);
boolean isANumberFlag = false;
String input;
int userX = 0;
do {
System.out.println("please enter a number: ");
input = reader.nextLine();
if (input.matches("\\d+")) {
userX = Integer.parseInt(input);
isANumberFlag = true;
}
else {
System.out.printf("you typed %s, which is not allowed \n", input);
System.out.println("Please enter numbers only, try again: ");
}
}
while (isANumberFlag == false);
System.out.println(userX);
This solution will only accept your input, if the entire line is numeric.
More information regarding int validation with a Scanner can be found on this topic