0

I've found that if I use the try with resources feature java provides which will automatically close of resources, I then can't use a boolean flag (or recursion) to resolve an InputMismatchException within a try catch as the catch block seems to be out of range of the scanner. As a result if an invalid character is entered e.g. a letter key for a menu, the that the enter key cannot be dismissed by sc.next() puts the programme into an infinite loop. I've attached a bit of sample code to demonstrate what I mean. Not sure if this is something that can be resolved or if it is just best to instantiate the scanner outside of the try catch block? I have tried instantiating the scanner outside of the try catch block and then closing it off with sc.close at the end of the method this works ok. I am just curious if there is a way around this as the try with resources is a useful feature in avoiding human error.

/** * @param args */ public static void main(String[] args) {

    displayMenuAndProcessUserOption();

}

public static void displayMenuAndProcessUserOption() {

    //Scanner sc = new Scanner(System.in); if scanner declared outside of try catch programme runs ok
    int userOption = 0;
    boolean flag = false;

    do {

        try(Scanner sc = new Scanner(System.in);) {
            do {

                System.out.println("1. Do something");
                System.out.println("2. Exit");

                userOption = sc.nextInt();

                switch (userOption) {
                case 1:
                    System.out.println("Does something");
                    break;
                case 2:
                    System.out.println("Exiting. Bye");
                    break;
                default:
                    System.out.println("Invalid num");

                }

            } while (userOption != 2);
            flag = true;

        } catch (InputMismatchException inputMismatchException) {
            System.err.println("Invalid input format. Please enter a numerical value from the menu options");
            flag = false;
            /**
             * when using the try with resources this is out of range for the Scanner: sc.
             * However without it the enter character is not dismissed and puts the
             * programme into an infinite loop
             */
            sc.next();
        }

    } while (!flag);
}

}

1 Answers1

0

You could use a try-catch-block around the sc.nextInt() call to avoid losing your scanner on the outside try-catch-block:

try(Scanner sc = new Scanner(System.in) {
    //program before first input
    boolean validInput = false;
    do {
        try {
            userOption = sc.nextInt();
            validInput = true;
        } catch (Exception e) {
            //exception handling
        }
    } while (!validInput);
}
//catch block
Itisdud
  • 41
  • 7