1

I'm trying to program a game, and I'm making methods to check the different sides of a player for terrain. I'm using a boolean method, but netbeans is telling me I don't have a return statement.

public boolean checkTerrainDown(Level levelToCheck){
    for(Terrain terrainToCheck: levelToCheck.levelTerrain){
        if(y+h<terrainToCheck.getY()){
            return true;
        }else{
            return false;
        }
    }
}
4
  • When your method has to return something you need to provide return statement for every possible execution path that can be taken. Commented Sep 25, 2013 at 22:31
  • 1
    It's a good practice to only have an only return statement! by the way , you didn't have to make a for for what you are doing.. you only are asking for the first element.. besides use return y+h < terraintoCheck.getY(); Commented Sep 25, 2013 at 22:33
  • 3
    @nachokk: No, it's really not. It's a good practice to make your code as clear as possible. Sometimes that means one return statement - sometimes it means multiple ones. Commented Sep 25, 2013 at 22:34
  • @JonSkeet you got it right, it's a personal decission that i don't like multiple returns most of the times, i think i only use multiple returns for the "easy cases" but a readable clean code is what we have to point :). Commented Sep 25, 2013 at 23:05

3 Answers 3

6

What if there is no Terrain to check? Then the body of the for loop never gets executed. You have no return statement after the for loop to account for this case. What would you have Java return in this case?

Place a return statement after the for loop to handle the case in which there's no Terrain in the Level's levelTerrain. That way, every possible case of execution will return something.

Sign up to request clarification or add additional context in comments.

Comments

1

if the for loop doesn't executed then there is no return statement will be executed.

Comments

1
public boolean checkTerrainDown(Level levelToCheck){
        //add this line
        boolean mark = false;
    for(Terrain terrainToCheck: levelToCheck.levelTerrain){
        if(y+h<terrainToCheck.getY()){
                //add this line,remove this //return true;
            mark = true;
            //add this line
            break;
        }
        //else{
            //return false;
        //}
    }
    //add this line
    return mark;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.