Search code examples
javamethodsbooleanreturn

java boolean method return statement


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

Solution

  • 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.