Reputation: 63
I am trying to create a method that checks if an input is a double that is greater than zero. Checking if it is indeed a double is working fine with my code, but, even though when entering negatives its prompts to reenter the value, in the end, after entering a positive value it returns the negative entered earlier
public static double isValid(double v){
Scanner scan = new Scanner(System.in);
if (scan.hasNextDouble()){
v = scan.nextDouble();
if (v<=0) {
System.out.println("You have to use a positive number");
isValid(v);
}
else {
return v;
}
}
else {
System.out.println("Thats not how it works");
isValid(v);
}
return v;
}
Upvotes: 1
Views: 1321
Reputation: 45750
You need to return the result of your recursive calls:
return isValid(v);
It's returning the last invalid value because after returning from the recursive call, execution continues down to the return at the bottom of the method, returning v
. At this point, v
is the last invalid value.
Upvotes: 2