Java——必须返回 boolean 类型(但我返回 true 或 false)

标签 java boolean return

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 using if - 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/

相关文章:

c - 在 C 中的函数中是否必须使用 "return"和 "void"?

java - 如何使用 HttpUrlConnection 在 Android 中构建 REST 客户端

java - 从对象数组列表中获取最大值?

java - 没有当前上下文

java - 编写一个使用 float 组和 boolean 值作为参数的 boolean 方法

PHP 类方法返回类型

java - Spring Web MVC 安全性花了很长时间才能完成页面加载

java - Android:回调 java.lang.NullPointerException 中的 sendBroadcast 未处理的异常

java swing keylistener 和线程

javascript - 等待一个函数返回一个值,然后再继续执行其他函数的其余命令