Alexander
Alexander

Reputation: 9

Why does my try/catch block keep looping?

When I run this, the code skips over input.nextInt(); and goes in circles:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    // Link user to programs (ToC)
    int loop = 1;

    do {
        try {
            System.out.println("Please choose a number: ");
            System.out.println("0. Exit");
            System.out.println("1. Calculator");
            int numChoice = input.nextInt();
            if (numChoice == 0) {
                System.exit(0);
            } else if (numChoice == 1) {
                System.out.println("Going to Calculator...");
                new Calculator();
            } else {
                System.out.println("Not a valid choice.");
            }
        }
        catch (Exception e) {
            System.out.println("Please input a number!");
        }
    } while (loop == 1);
}

It seems to be skipping int numChoice for whatever reason. Also, please don't be too technical. I just code for my leisure.

Upvotes: 1

Views: 551

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Your loop goes in circles for two reasons:

  • You try for nextInt, but you do not clear out the input buffer on failure, and
  • Even if you did clear input in the catch, your loop would still go on, because there are no assignments of the loop variable which is supposed to stop your loop.

Upvotes: 3

Related Questions