0

So this is an infitine loop until number 6 is entered, if a number that is not a choice is entered it pritns the error and start the loop again. But, when the input is not an int it prints the menu over and over and it never stops. The program should print error aswell if something that is not an int is entered. help

Scanner sc = new Scanner(System.in);
        int choice;
        do {
            
            System.out.println("enter 1 to print names");
            System.out.println("enter 2 to add name");
            System.out.println("enter 3 to clear all names");
            System.out.println("enter 4 to save name to file");
            System.out.println("enter 5 to load file names");
            System.out.println("enter 6 to quit");
            System.out.println("Please input the number of your choice: ");
            try {
                choice = sc.nextInt();
                System.out.print("\n");
            }
            catch(InputMismatchException e) {
                //invalid input entered,  clear it,send error, and set option to 0
                choice = 0;
            }
            switch (choice) {
            case 1:
                printNames();
                break;
            case 2:
                sc.nextLine();
                addName(sc);
                break;
            case 3:
                clearNames();
                break;
            case 4:
                sc.nextLine();
                saveNames(sc);
                break;
            case 5:
                sc.nextLine();
                loadNames(sc);
                break;
            case 6:
                System.out.println("program closed!");
                break;
            default:
                System.out.println("Invalid choice.\n");
                break;
            }
        } while(choice!=6);
comms
  • 3
  • 1
  • so How would you change the code? I think you are talking about the try-catch functoin right? – comms Apr 07 '22 at 17:48
  • `System.out.println();` is the same as `System.out.print("\n");`. You **could** change `choice` to a String variable and initialize it to Null String (""), then use `choice = sc.nextLine();`. Then change the `case` elements to String, for example: `case "1":` etc. Then there would be no need for a `try/catch`. The `while` condition would need to be something like: `while (!choice.equals("6"));`. `default:` within the `switch/case` block doesn't need a `break;` there since there is no further worry of fall-through at the end of the block. – DevilsHnd - 退職した Apr 07 '22 at 21:40

0 Answers0