Reputation: 59
I just started writing recursive methods. One of my methods for powers of ten is giving me a missing return type error.
public static double powerOfTen(int n)
{
if (n == 0)
return 1;
if(n > 0)
return (10 * powerOfTen(n - 1));
if(n < 0)
return (1 / powerOfTen(n - 1));
}
I'm pretty new so any explanation will be appreciated.
////// Edit This worked out for me, for negative and positive powers of ten. Thanks for your help :D
public static double powerOfTen(int n)
{
if(n > 0)
return (10 * powerOfTen(n - 1));
if(n < 0)
return (1 / powerOfTen( (-1)*(n) ));
return 1;
}
Upvotes: 2
Views: 297
Reputation: 121998
Please change your code:
The point is clear: If that statement is false
, I don't want the function to continue,so i'l return
which you missed.
public static double powerOfTen(int n)
{
if(n>1){ //check for positive n value
if(n > 0){
return (10 * powerOfTen(n - 1));
}else if(n < 0){
return (1 / powerOfTen(n - 1));
}
}
return something; //here error
}
As a side note for best practices please use { }
between if else statements.
Upvotes: 0
Reputation: 180
The compiler is not doing a range-coverage test so it doesn't notice that your code covers all possible values of int n, and thus the error.
Upvotes: 1
Reputation: 12670
Try:
public static double powerOfTen(int n)
{
if(n > 0)
return (10 * powerOfTen(n - 1));
if(n < 0)
return (1 / powerOfTen(n - 1));
return 1;
}
The compiler thinks it can't guarantee that there's always a value being returned since all the returns are in if
statements. Doing it this way takes away the confusion
Upvotes: 3