-3

It's just a simple little method that gets user input to convert an integer from decimal to binary. It uses do-while loops to restart and verify valid input. When it catches an InputMismatchException, it starts to infinitely loop this:

Must enter a positive integer, try again.
Enter positive integer for binary conversion:

I don't know why the Scanner isn't causing the program to wait for new input when I call nextInt().

Here's the code for the method:

public static void main (String[] theArgs) {
    final Scanner inputScanner = new Scanner(System.in);
    boolean invalidInput = false;
    boolean running = true;
    int input = 0;
    do {
        do {
            System.out.println("Enter positive integer for binary conversion:");
            try {
                input = inputScanner.nextInt();
                if (input < 1) {
                    System.out.println("Must be a positive integer, try again.");
                    invalidInput = true;
                } else {
                    invalidInput = false;
                }
            } catch (final InputMismatchException e) {
                System.out.println("Must enter a positive integer, try again.");
                invalidInput = true;
            }
        } while (invalidInput);
        System.out.println(StackUtilities.decimalToBinary(input));
        System.out.println("Again? Enter 'n' for no, or anything else for yes:");
        if (inputScanner.next().equals("n")) {
            running = false;
        }
    } while (running);
}
Jake M.
  • 7
  • 2
  • Have you tried printing printing `input` ? Do you know which version of ""Must be a positive integer, try again." is printed (are you sure it is the one in the exception?). Lookup "how to debug small programs" for more hints. – John3136 Jan 17 '19 at 03:42
  • If you enter an invalid value, `nextInt()` throws `InputMismatchException` **without consuming the invalid value**, so when you loop back, it's still there. Add e.g. `next()` inside the `catch` block to consume the invalid value. – Andreas Jan 17 '19 at 03:43

1 Answers1

4

You need to clear the buffer when user enters the wrong type of input, Just use inputScanner.next() or inputScanner.nextLine() in catch block to clear the buffer

catch (final InputMismatchException e) {
      inputScanner.nextLine();
            System.out.println("Must enter a positive integer, try again.");
            invalidInput = true;
        }
Deadpool
  • 29,532
  • 9
  • 38
  • 73