green_claws
green_claws

Reputation: 13

a simple Java recursion with some kind of bug I don't get

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

Answers (5)

Bohemian
Bohemian

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

Joop Eggen
Joop Eggen

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

Reimeus
Reimeus

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

Mik378
Mik378

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

Jeanne Boyarsky
Jeanne Boyarsky

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

Related Questions