此方法必须返回int,java类型的结果

时间:2018-04-22 09:59:33

标签: java return

我想写一个运行rekursiv的程序。它应该添加两个变量。但我只允许添加1或减1.我对.Java文件。他们每个人都有一个班级。

这是主要课程:

  package rekursion;

    public class Main_function {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int a= 5;
            int b= 3;

            int result = rekursion.Addierer_Multiplizierer.add(a, b);

            System.out.print(result);
        }

    }

那就是算法:

package rekursion;

public class Addierer_Multiplizierer {

    public static int add(int x, int y){      // here it Shows an error, 
        if (x >= 0 && y >= 0){            // because the return value
            if(y==0){                 // is not of type int
                return x;       
            }
            return add(++x, --y);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您的方法必须在其所有执行分支中都有返回值。

问题是你是否应该支持负面投入。

如果没有,您可以将方法更改为:

public static int add(int x, int y)
{
    if(y == 0) {
        return x;
    }
    return add(++x, --y);
}

否则,您必须检查y的签名,并决定是增加还是减少y才能将其带到0

public static int add(int x, int y) 
{
    if (y == 0) {
        return x;
    } else if (y > 0) {
        return add(++x, --y);
    } else {
        return add(--x, ++y);
    }
}

或者,如果您更喜欢一个班轮:

public static int add(int x, int y) {
    return y == 0 ? x : y > 0 ? add(++x, --y) : add(--x, ++y);
}

答案 1 :(得分:-1)

让我格式化一下让你更清楚......

 public static int add(int x, int y){ 
        if (x >= 0 && y >= 0){
            if(y==0){
                return x;       
            }
            return add(++x, --y);
         }
         // ok, and what if not?
    }

你看到了问题吗?在第一个if-block中你总是返回一些东西......但是如果(x >= 0 && y >= 0)不正确怎么办?没有回报。所以你错过了那些东西。

相关问题