Reputation: 57
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.
"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?
Upvotes: 2
Views: 287
Reputation: 3702
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.
Upvotes: 2
Reputation: 8003
Why would you expect something else? You probably print result from the very first method call and since it's 0, that's what it'll return.
Instead you should return whatever result the recursive call returned.
Upvotes: 0