dimanche 26 mars 2017

Constant loop when InputMismatchExpection has been caught instead of retrying/scanning keyboard input again

Whenever an Input Mismatch is caught there is an infinite loop (example entering ];), instead of trying the "option = scanner.nextInt();" again. However typing a normal invalid input like "7" works fine. I don't want to use a "break;" because I want it to stay in the loop and scan input again so how would I approach this problem?

    System.out.println("Select option [1, 2, 3, 4] :> ");

    int option = 0;
    while(runOptions){
        try{
            option = scanner.nextInt();
        }catch(InputMismatchException e){
            System.out.println("ERROR Try Again...\n");
            System.out.println("\nSelect option [1, 2, 3, 4] :> \n");

        }


        if(option != 4){
            if(option == 1){
                doAddOption();
                runLoop = false;
    }
    else if(option == 2){
                doDelete();
                runLoop = false;
    }
    else if(option == 3){
                doDeleteRegistry();
                runLoop = false;
    }
    else{
          System.out.println("INVALID Try again..");
    }   
}

Aucun commentaire:

Enregistrer un commentaire