import java.util.InputMismatchException; import java.util.Scanner;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean nvalid = true; // boolean to get out of do while when user input number
int a = 0;
System.out.println("enter number a");
do {
try {
a = sc.nextInt();
nvalid = true;
} catch (InputMismatchException e) {
System.out.println("please enter number only");
nvalid = false; //make the boolean false so do while will let user enter number again.
}
} while (nvalid == false);
System.out.println("out of do while");
}
Hi , i am using netbeans to practice java exception, i want to catch exception when user does not enter number.
The code above causes infinite loop and prevents user from entering value for variable a
.