简体   繁体   中英

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

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.

如果未执行for loop则不会执行return语句。

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

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