简体   繁体   中英

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.

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;
}

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM