Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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?



/**
	 * @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);
	}

}


What I have tried:

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.
Posted
Updated 17-Mar-22 23:25pm

1 solution

The Scanner object only exists within the try block, so you cannot refer to it in the catch. And you specifically should not be doing so. You should rework the code so that the Scanner is instantiated before the try, and is not referred to in the catch. The only thing that the catch should do is to set a flag telling the do loop to ask the user to repeat their input.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900