Search code examples
javainputmismatchexception

how to handle this InputMismatchException?


In the code below I'm getting InputMismatchException at line 80 even before I'm giving the input. Why is this?

try {
    loop:while(true)
    {
        choice=sc.nextInt();
        switch (choice) {
            case 1: 
                term=3;
                break loop;
            case 2:
                term=6;
                break loop;
            default:
                System.out.println("Invalid Input.. Enter again");
                choice=sc.nextInt();
        }
    } 
}
catch (InputMismatchException e2) {
    System.out.println("Wrong Format!! Enter a number");
    choice=sc.nextInt();  //line 80
}

Solution

  • Consume the end of line:

    catch (InputMismatchException e2) {
        System.out.println("Wrong Format!! Enter a number");
        sc.nextLine(); // add this
        choice=sc.nextInt();  //line 80
    }
    

    In addition, you probably shouldn't have two choice=sc.nextInt(); in your loop.

    And you want to put the try-catch inside the loop, in order to stay in the loop after the exception is caught.