下面是java方法的代码,但不会编译。我正在使用Eclipse,每当我尝试编译我的代码时,它会说:
此方法必须返回
int
类型的结果。
a,b,c
已经过了
声明为int
,因此返回类型为int
。
public static int f(int a, int b, int c) {
if ((a < b) && (b < c))
return a;
else if ((a >= b) && (b >= c))
return b;
else if ((a == b) || (b == c) || (a == c))
return c;
}
答案 0 :(得分:12)
您的if
条件并非详尽无遗。如果a > b
和b < c
,则所有条件都不匹配,并且您的函数不会返回任何内容,这就是Eclipse抱怨的原因。
在结尾处添加默认return
语句,无论是条件还是else
块。
答案 1 :(得分:4)
基本上它不会编译,因为你没有一个else子句,因为没有一个案例是正确的。然后该方法没有回报。因此编译器会要求返回int。
public static int f(int a, int b, int c) {
if ((a < b) && (b < c))
return a;
else if ((a >= b) && (b >= c))
return b;
else if ((a == b) || (b == c) || (a == c))
return c;
else{
System.out.println("No clause matched");
return 0; //or something else
}
}
答案 2 :(得分:2)
如果if-else块没有触发会发生什么? 你错过了return语句,你可以用这种方式
windowButtonMotion_Fcn
创建一个返回点并在方法的正文中尝试分配一个 相应的值,最后,返回它。
答案 3 :(得分:1)
如前所述,您的功能可以在没有返回的情况下结束。 如果不能发生这种情况(其中一个条件应该始终为真),您也可以以例外结束:
public static int f(int a, int b, int c) throws Exception
{
if ((a < b) && (b < c))
{
return a;
}
else if ((a >= b) && (b >= c))
{
return b;
}
else if ((a == b) || (b == c) || (a == c))
{
return c;
}
throw new Exception("Input not valid");
}
这样调用者可以处理异常或记录出错的地方。