Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asking for input after catching an exception

I want the user to enter a number which is scanned by the following code:

scanner.nextInt();

If a user enters a string instead, the program throws InputMismatchException, which is obvious. I want to catch the exception in such a way that the program prompts the user to enter an input until the user enters an integer value.

Scanner scanner = new Scanner(System.in);
while(true) {
    try {
        System.out.println("Please enter a number: ");
        int input = scanner.nextInt();
        System.out.println(input);
        //statements
        break;
    }
    catch(InputMismatchException | NumberFormatException ex ) {
        continue;
    }
}

This code creates an infinite loop if a string is entered.

like image 891
h-rai Avatar asked Aug 30 '12 06:08

h-rai


2 Answers

The answer to my problem is as follows:

Scanner scanner = new Scanner(System.in);
while(true) {
    try {
        System.out.println("Please enter a number: ");
        int input = scanner.nextInt();
        System.out.println(input);
        //statements
        break;
    }
    catch(InputMismatchException | NumberFormatException ex ) {
        scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input
        continue;
    }
}
like image 181
h-rai Avatar answered Nov 07 '22 14:11

h-rai


Put Scanner scanner = new Scanner(System.in); within your while loop.

Scanner scanner;
while(true) {    
    try {
        System.out.println("Please enter a number: ");
        scanner = new Scanner(System.in);
        int input = scanner.nextInt();
        System.out.println(input);
        //statements
        break;
    }
    catch(InputMismatchException | NumberFormatException ex ) {
        System.out.println("I said a number...");
    }
}
like image 21
sp00m Avatar answered Nov 07 '22 16:11

sp00m