无法弄清楚为什么简单方法在Java中无限循环

时间:2019-01-17 03:38:30

标签: java java.util.scanner infinite-loop

这只是一个简单的小方法,可让用户输入将整数从十进制转换为二进制。它使用do-while循环重新启动并验证有效输入。当捕获到InputMismatchException时,它将开始无限循环:

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

当我调用nextInt()时,我不知道为什么扫描程序没有导致程序等待新输入。

这是该方法的代码:

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);
}

1 个答案:

答案 0 :(得分:4)

当用户输入错误的输入类型时,您需要清除缓冲区,只需在inputScanner.next()块中使用inputScanner.nextLine()catch来清除缓冲区

catch (final InputMismatchException e) {
      inputScanner.nextLine();
            System.out.println("Must enter a positive integer, try again.");
            invalidInput = true;
        }