gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:12:18 25 4
gpt4 key购买 nike

我想编写一个可以rekursiv运行的程序。它应添加两个变量。但我只允许加 1 或减 1。我对 .Java 文件进行了处理。他们每个人都有一个类(class)。

这就是主类:

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

最佳答案

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

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

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

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

关于java - 该方法必须返回int类型的结果,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com