If the user enter a non-numeric value for example "Hello", I want to give the user a new chance to enter a numeric value until he succeeds.
Running the code below, the text "This is not a numeric value. Enter a numeric value: ", will show in the console, if the user enters a non-numeric value. However, the user will not be able to enter a new value. Because the error message "Exception in thread..." will show and stop the program.
How do I solve this?
Edit!
New code (This code works, except it stops the program completely. Every method called afterwards, won't run.) Edit2! It did not work!
int number;
do {
try {
System.out.println("Enter a numeric value: ");
number = Integer.parseInt(s.nextLine());
if (s.nextInt() != (int)number) {
throw new NumberFormatException();
}
break;
}
catch (NumberFormatException e) {
System.out.println("This is not a numeric value. Enter a numeric value: ");
}
} while (true)
Old code
int number;
try {
Scanner s = new Scanner(System.in);
System.out.println("Enter a numeric value: ");
number = s.nextInt();
if (number != (int)number) {
throw new Exception();
}
}
catch(Exception e) {
do {
System.out.println("This is not a numeric value. Enter a numeric value: ");
number = s.nextInt();
} while (number != (int)number);
}