Reputation: 13
public class test {
public static void main (String[] args) {
System.out.print (prod (1, 2));
}
public static int prod (int m, int n){
if (m == 0) {
return n+1;
} else if(m>0 && n == 0){
return prod (m-1, 1);
} else if(m>0 && n >0){
return prod(m-1,prod(m,n-1));
}
}
}
there's something wrong with:
public static int prod (int m, int n){
but I cannot figure out what it is.
Upvotes: 0
Views: 96
Reputation: 425208
You must return a value, and when your if
conditions are all false
, it won't.
Also, your else
statements are redundant: if the execution of the method terminates due to an if
, there is no "else".
Change your code to something like this:
if (m == 0)
return n + 1;
if (m > 0 && n == 0)
return prod(m - 1, 1);
if (m > 0 && n > 0) {
return prod(m - 1, prod(m, n - 1));
// return a default value if no conditions met
return 0;
I have no idea what "prod" means, or what the intention is, so you'll have up figure out for yourself that the appropriate default value is. I chose 0
as a starting point.
Upvotes: 2
Reputation: 109593
Assuming that natural numbers are intended.
public static int prod(int m, int n){
if (m <= 0) {
return n+1;
} else if (n <= 0){
return prod(m-1, 1);
} else {
return prod(m-1, prod(m, n-1));
}
}
If with "weird" you mean termination of the recursion: that I did not see.
Upvotes: 0
Reputation: 159844
The method must return a value in all cases. You can add an additional return
statement outside if
statement block
public static int prod (int m, int n) {
if (m == 0) {
return n+1;
} else if(m>0 && n == 0) {
return prod (m-1, 1);
} else if(m>0 && n >0) {
return prod(m-1,prod(m,n-1));
}
return n;
}
Upvotes: 2
Reputation: 22191
Just to shorten the @Reimeus's solution: (explaining my comment above)
if (m == 0)
return n + 1;
if (m > 0 && n == 0)
return prod(m - 1, 1);
if (m > 0 && n > 0)
return prod(m - 1, prod(m, n - 1));
return n;
Without needing curly braces and redundant useless else
keywords in this case.
Upvotes: 0
Reputation: 12266
There is no else statement at the end of the if/else chain. What happens if m is -1? You many know that never happens, but the compiler does not.
Upvotes: 2