Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive method with exception, logical error

I am trying to make a code which inserts a user input until the input is correct (double), it will loop again until the input is correct.

Below is the code:

private static double variableNumberInput(String variableName, Scanner userInput) {
    double userInputNumber = 0;
    try {
        System.out.println(String.format("Input value: %s", variableName));
        userInputNumber = Double.valueOf(userInput.nextLine());
    } catch (Exception exception) {
        System.out.println("Please try again");
        variableNumberInput(variableName, userInput);
    }
    return userInputNumber;
}

It worked perfectly as I wanted… , until I test it and purposely insert a wrong input first (using a string), after that inserted the correct input. The result it returns 0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Input value: X"
incorrect input
"Please try again"
"Input value: X"
1
returns -> 0

I did try to debug it, and it apparently returns the correct value, but somehow after the input is correct it then calls the method again inside the catch block only to return 0.

Can’t figure out why it behave that way, can someone please help me understand?

>Solution :

You are not saving the result of your recursive calls. Try this:

private static double variableNumberInput(String variableName, Scanner userInput) {
    double userInputNumber = 0;
    try {
        System.out.println(String.format("Input value: %s", variableName));
        userInputNumber = Double.valueOf(userInput.nextLine());
    } catch (Exception exception) {
        System.out.println("Please try again");
        userInputNumber = variableNumberInput(variableName, userInput);
    }
    return userInputNumber;
}

Notice the change in the catch block.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading