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); } }
Scanner
try
catch
do
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)