What is the best way to read number from console using scanner?

user5301398 :

I'm trying to write a function to validate the user's input. It only returns when the user inputs a double number.

private static double getDouble(String name) {
    double res = 0;
    Scanner s = new Scanner(System.in);
    while (true) {
        System.out.println("Please input " + name + ":");
        if (s.hasNextDouble()) {
            res = s.nextDouble();
            break;
        }
        else s.nextLine();
    }
    s.close();
    return res;
}

However, it only works first time. If I call the function second time right after the first time, the nextLine() will throw an exception.

double length = 0, width = 0;
length = getDouble("length of picture");
width = getDouble("width of picture");

Please see the Output Screenshot

Could someone tell me what the mistake I have made here? And how to fix/avoid it?

Thank you.

Mark :

I have made another way for getting user input. Just refer to the code and code comments for details.

private static double getDouble(String name) {
    double res = 0;
    Scanner s = new Scanner(System.in);
    while (true) {
        try {
            System.out.print("Please input " + name + ":");
            res = Double.parseDouble(s.nextLine()); // Just get the user input as a string then try to convert it into a double
            break; // if there is no error in the string to double conversion it means that the input is valid, thus break the loop
        } catch (Exception e) { // catch possible errors in case the input is invalid
            System.out.println("Your input is invalid!"); // print desired error message then the loop will execute again getting another user input
        }
    }
    s.close();
    return res;
}

EDIT It is because you have close the scanner instance after the method. Refer to this why that won't work. You could also refer to that for alternatives.

If you want to use hasNextDouble then you could either pass the scanner as a parameter to your getDouble method or declare the scanner as a class variable. Both will result to only declaring and closing 1 Scanner.

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        double tmp = getDouble(s, "Tmp");
        double tmp2 = getDouble(s, "Tmp");
        s.close();
    }

    private static double getDouble(Scanner s, String name) {
        double res = 0;
        while (true) {
            System.out.println("Please input " + name + ":");
            if (s.hasNextDouble()) {
                res = s.nextDouble();
                break;
            } else
                s.nextLine();
        }
        return res;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310936&siteId=1