使用nextInt()和循环时,扫描程序会一直跳过输入

时间:2013-03-20 05:30:26

标签: java loops java.util.scanner next

我正在使用while循环来确保输入到scanner对象的值是一个整数:

while (!capacityCheck) {
        try {
            System.out.println("Capacity");
            capacity = scan.nextInt();
            capacityCheck = true;
        } catch (InputMismatchException e) {
            System.out.println("Capacity must be an integer");
        }
    }

但是,如果用户没有输入一个整数,当它应该返回并接受另一个输入时,它只是重复打印“容量”,然后输入捕获中的输出而不需要更多输入。我该如何阻止它?

5 个答案:

答案 0 :(得分:3)

scan.nextLine();

将这段代码放在catch块中,使用非整数字符以及保留在缓冲区中的新行字符(因此,无限打印catch sysout),如果你给出了错误的输入。

当然,还有其他更简洁的方法可以达到你想要的效果,但我想这需要在代码中进行一些重构。

答案 1 :(得分:0)

尝试将其放在循环的末尾 -

scan.nextLine();

或者更好地把它放在catch块中。

    while (!capacityCheck) {
        try {
            System.out.println("Capacity");
            capacity = scan.nextInt();
            capacityCheck = true;
        } catch (InputMismatchException e) {
            System.out.println("Capacity must be an integer");
            scan.nextLine();
        }
    }

答案 2 :(得分:0)

使用以下内容:

while (!capacityCheck) {
        System.out.println("Capacity");
        String input = scan.nextLine();
        try {
            capacity = Integer.parseInt(input );
            capacityCheck = true;
        } catch (NumberFormatException e) {
            System.out.println("Capacity must be an integer");
        }
    }

答案 3 :(得分:0)

试试这个:

while (!capacityCheck) {
    try {
        System.out.println("Capacity");
        capacity = scan.nextInt();
        capacityCheck = true;
    } catch (InputMismatchException e) {
        System.out.println("Capacity must be an integer");
        scan.nextLine();
    }
}

答案 4 :(得分:0)

我认为不需要try / catch或capacityCheck,因为我们可以访问方法hasNextInt() - 它检查下一个标记是否为int。例如,这应该做你想要的:

    while (!scan.hasNextInt()) { //as long as the next is not a int - say you need to input an int and move forward to the next token.
        System.out.println("Capacity must be an integer");
        scan.next();
    }
    capacity = scan.nextInt(); //scan.hasNextInt() returned true in the while-clause so this will be valid.
相关问题