mardi 3 avril 2018

How do I effectively clear a buffer in Java?

This is a method for the main class of this problem.

I have an issue when the user inputs a non-numeric value for the requested information.

Example)

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:

This is the output that occurs when this method is called. How do i correct this?

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

Aucun commentaire:

Enregistrer un commentaire