-3

For one of my assignments we are supposed to try to catch a InputMismatchException and tell the user to input a given option (In this case it can be 1,2,3,4 and nothing else). For some reason, whenever I try to make the try catch block it makes the user enter input twice and it still crashes the program. Here is what I have:

do {
      Scanner menuOptions = new Scanner(System.in);
      System.out.println("1. Get another card");
      System.out.println("2. Hold hand");
      System.out.println("3. Print statistics");
      System.out.println("4. Exit"+ "\n");
      System.out.println("Choose an Option: ");
      int selectedOption = menuOptions.nextInt();

      try{
      selectedOption = menuOptions.nextInt();
      }

      catch(InputMismatchException e){
      System.out.println("Invalid input! Please select between options 1,2,3,4")
      }


      if (selectedOption == 1) {
      //proceeds to do what is instructed if user input is 1}
      else if (selectedOption ==2{
      //proceeds to do what is instructed if user input is 2}
     else if (selectedOption == 3) {
      //proceeds to do what is instructed if user input is 3}
     else if (selectedOption ==4{
      //proceeds to do what is instructed if user input is 4}

Any idea on how I can make this work?

Peter
  • 1
  • 1
  • 1
  • [Check Out this answer](https://stackoverflow.com/questions/12702076/java-try-catch-with-inputmismatchexception-creates-infinite-loop) Hope this helps! – P. Jaiswal Sep 30 '17 at 02:33

1 Answers1

1

It's because you call menuOptions.nextInt() twice. Once on initialization, and a second time in the try catch block. I'm assuming you have code that you want to run until the user enters a valid input, being 1, 2, 3, or 4.

Try this:

int selectedOption;
while(true) {
    try {
        selectedOption = menuOptions.nextInt();
        break;
    } catch(InputMismatchException ime) {
        System.out.println("Invalid input! Please select between options 1,2,3,4");
        menuOptions = new Scanner(System.in);
    }
}
Ryan
  • 727
  • 2
  • 14
  • 31
  • I'm sorry can you explain this a little bit more to me, I'm kind of lost. I tried what you said but the program still crashed. – Peter Sep 30 '17 at 02:43