如何有效清除Java中的缓冲区?

时间:2018-04-03 20:08:25

标签: java loops if-statement buffer do-while

这是针对此问题主要类的方法。

当用户输入所请求信息的非数字值时,我遇到了问题。

实施例)

Enter a distance in meters: jam
Incorrect value. Please select a distance in meters greater than zero.

Enter a distance in meters: Incorrect value. Please select a distance greater than zero. 

Enter a distance in meters:

这是调用此方法时发生的输出。我该如何纠正这个?

public static double validDistance (String prompt,
                                    double minValue) {

    Scanner keyboard = new Scanner (System.in);
    double value;
    String errorMessage = "Incorrect value. Please select a distance in "
            + "meters greater than zero\n";
    // Protects distance input from incorrect value 
    // (non-numeric or too low)
    do {
        System.out.print(prompt);
        if (keyboard.hasNextDouble()) {
            value = keyboard.nextDouble();
            if (value <= minValue) {
                System.out.println(errorMessage);
            } else {
                break; // Exit loop
            }
        } else {
            System.out.println(errorMessage);
            keyboard.nextLine(); // Clears buffer
        }
    } while (true);
    return value;
}

1 个答案:

答案 0 :(得分:0)

我意识到这并没有直接回答你的问题。

我个人发现处理Scanner缓冲区非常烦人,所以我更喜欢一行一行地阅读并自己进行处理。例如:

public static double validDistance(String prompt, double minValue)
{
    Scanner keyboard = new Scanner(System.in);
    String errorMessage = "Incorrect value. Please select a distance in meters greater than zero\n";
    while (true) {
        System.out.print(prompt);
        String line = keyboard.nextLine();
        try {
            double result = Double.parseDouble(line);
            if (result >= minValue) {
                keyboard.close(); // You should always close a Scanner when you're done!
                return result;
            }
        } catch (NumberFormatException e) {
        }
        System.out.println(errorMessage);
    }
}