0
int choice = 0;

    while ((choice != 1) || (choice !=2)){

        System.out.println("1. Option 1");
        System.out.println("2. Option 2");

        try{

        choice = scanner.nextInt();

        }

        catch(InputMismatchException e){
            System.out.println(e);
        }

        if (choice == 1){
            System.out.println("Option 1");
            break;
        }

        if (choice == 2){
            System.out.println("Option 2");
            break;
        }

        System.out.println("Please enter a valid choice.");

    }

I am trying to handle the case where a non int is entered. Why does this spin into an infinite loop? It worked fine before I tried to add in the try catch block.

unskilledidiot
  • 409
  • 1
  • 5
  • 10
  • But then the program finishes, i want it to loop back so you can enter in another value. – unskilledidiot Jun 14 '16 at 09:54
  • 1
    You need to consume the newline token. See http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods. – Andy Turner Jun 14 '16 at 09:55

2 Answers2

0

Of course it will, because you are trapping the error inside the while loop and not setting any condition to exit the loop when the error is caught, so you will never exit.

Either add another condition to the while loop to exit on error or set choice to 1 or 2 when an error occurs, or break when an error is detected.

    int choice = 0;

    while ((choice != 1) || (choice !=2)) {
      System.out.println("1. Option 1");
      System.out.println("2. Option 2");

      try{
        choice = scanner.nextInt();
      } catch(InputMismatchException e) {
        System.out.println(e);
      }
      switch(choice) {
      case 1:
        System.out.println("Option 1");
        break;
      case 2:
        System.out.println("Option 2");
        break;
      default:
        System.out.println("Please enter a valid choice.");
        break; 
      }
    }
SPlatten
  • 4,487
  • 7
  • 32
  • 87
  • Hi, I want to make it so when the error is caught it goes back to the start of the loop so a proper value can be entered. How can I do this? – unskilledidiot Jun 14 '16 at 09:55
  • You need to flag an error has occurred then display an error before the entry if an error was detected, clear the flag and start over. – SPlatten Jun 14 '16 at 09:57
0

replace your try catch with

try{
    choice = Integer.parseInt(scanner.next());

} catch(NumberFormatException e){
    System.out.println("Enter a valid choice");
}