Why can't I get the 'else' to work in this boolean? error: void methods cannot return value

I’m trying to set a boolean expression to return true or false depending on whether getDrinkTime() is greater or less than 4 but I keep getting the error "void methods cannot return a value" on the "else { return false; } line. Am I missing something or is something not setup properly?

package sct;

public class Dog {
public String Dog;
public int DrinkTime;
public static boolean getDrinkTime;


public int setDrinkTime(int time) {
    return time;

}
public int getDrinkTime() {
return DrinkTime;
}

public static boolean needsToGo() {
int time = 3;
if (time > 4);
    return true;
}
else {
    return false;
}

public static void main(String[] args) {
    if (needsToGo()==true) {
    System.out.println("True");
    }else {
        System.out.println("False");
        }
}
}

>Solution :

It appears you have made a type in your needsToGo() Method:

public static boolean needsToGo() {
int time = 3;
if (time > 4); //<-- Change this Semicolon to a {
    return true;
}
else {
    return false;
}

Also, it would be better to write

return time > 4;

Because time > 4 will result in either true or false already, so no need to resolve this with an if statement.

Leave a Reply