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
java boolean method return statement
提问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 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?
如果没有Terrain
检查怎么办?然后for
循环体永远不会被执行。您return
在for
循环之后没有任何语句来说明这种情况。在这种情况下,您希望 Java 返回什么?
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.
放置一个return
语句后for
循环处理中没有的情况下Terrain
在Level
的levelTerrain
。这样,每个可能的执行案例都会return
有所作为。
回答by Yellow Flash
if the for loop
doesn'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;
}