java布尔方法返回语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19016258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:24:13  来源:igfitidea点击:

java boolean method return statement

javamethodsbooleanreturn

提问by user2817232

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.

我正在尝试编写游戏程序,并且正在制定方法来检查玩家不同侧面的地形。我使用的是布尔方法,但 netbeans 告诉我我没有 return 语句。

public boolean checkTerrainDown(Level levelToCheck){
    for(Terrain terrainToCheck: levelToCheck.levelTerrain){
        if(y+h<terrainToCheck.getY()){
            return true;
        }else{
            return false;
        }
    }
}

采纳答案by rgettman

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

如果没有Terrain检查怎么办?然后for循环体永远不会被执行。您returnfor循环之后没有任何语句来说明这种情况。在这种情况下,您希望 Java 返回什么?

Place a returnstatement after the forloop to handle the case in which there's no Terrainin the Level's levelTerrain. That way, every possible case of execution will returnsomething.

放置一个return语句后for循环处理中没有的情况下TerrainLevellevelTerrain。这样,每个可能的执行案例都会return有所作为。

回答by Yellow Flash

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

如果for loop没有执行,则不会执行 return 语句。

回答by sunysen

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