简体   繁体   中英

Java — Must return type boolean (But I am returning true or false)

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

}

I am confused, why I am getting an error where the public method parrotTrouble is underlined saying it must return a boolean, which I currently have?

Compiler says you need to return some value since your method return type is boolean .

You have returned false in If condition , and return true in else if condition .

you need to return something outside of if/else if as well.

something as below, as per comments from @Andreas, code can be reduced to below

Original as per 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
    }

Edit

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.

public boolean parrotTrouble(boolean talking, int hour) {
    boolean answer = false;
    if(talking == false){
        answer = false;
        }
        else if(hour < 7 || hour >20){
            answer = true;
            }
    return answer;
    }

Thank you for your help, I changed my code to this and it worked correctly and answered the question <3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM