public class CodingBat {
public static void main(String[] args){
CodingBat object = new CodingBat();
System.out.print(object.parrotTrouble(true,20));
}
public boolean parrotTrouble(boolean talking, int hour) {
if(talking == false){
return false;
}
else if(hour > 7 || hour >20){
return true;
}
}
}
我很困惑,为什么我会收到一个错误,其中公共(public)方法 parrotTrouble 带有下划线,表示它必须返回我目前拥有的 boolean 值?
最佳答案
编译器表示您需要返回一些值,因为您的方法返回类型是 boolean
。
您在 If 条件中返回 false
,在 else if 条件中返回 true
。
您还需要在 if/else if 之外返回一些内容。
如下所示,根据@Andreas的评论,代码可以减少到下面
根据OP原创
public boolean parrotTrouble(boolean talking, int hour) {
if (talking == false) {
return false;
} else if (hour > 7 || hour > 20) {
return true;
}
return booleanValue; // can be true/false as per your logic
}
编辑
public boolean parrotTrouble(boolean talking, int hour) {
return (talking && (hour > 7 || hour > 20));
}
As pointed by @Codebender, wither use
if else condition
, then no need to return boolean value at the last, but if you are usingif - else if
you have to return boolean value at the last. As compiler is also not sure that it will go in one of the conditions surely.
关于Java——必须返回 boolean 类型(但我返回 true 或 false),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193441/