[英]How can i check if every object in my ArrayList has a value equal to zero?
I am creating a game and need to check if all players in the playerList have played all their games. 我正在创建一个游戏,需要检查playerList中的所有玩家是否都玩过所有游戏。 I do this by taking away from the noOfGames variable until it is 0. My problem with my code right now is that if the last player in the playerList have finished, the game ends. 我通过从noOfGames变量中删除变量直到它为0来实现此目的。我现在的代码问题是,如果playerList中的最后一个玩家结束,则游戏结束。 Here is my code: 这是我的代码:
public boolean isGameOver(){
boolean allEqualsZero = true;
for(Player i : playerList){
if (i.getNoOfGames() != 0){
allEqualsZero = false;
}
else{
allEqualsZero = true;
}
}
return allEqualsZero;
}
Your boolean
variable may change for each player. 您的boolean
变量可能会因每个玩家而异。
The game is over if someone has something to play, so if someone still has to play, directly return false
. 如果有人要玩,游戏就结束了,所以如果有人仍然要玩,请直接返回false
。
If no one has something, return true
at the end. 如果没有人,则最后返回true
。
public boolean isGameOver() {
for (Player i : playerList) {
if (i.getNoOfGames != 0) return false;
}
return true;
}
You may otherwise use a stream
if you're using java-8 如果您使用的是Java-8,则可以使用stream
public boolean isGameOver(){
return playerList.stream()
.allMatch(x -> x.getNoOfGames() == 0);
}
The problem with this code is that it returns whether the last player equals to 0
. 此代码的问题在于,它返回最后一个玩家是否等于0
。 So what you should do, is if any one player equals to 0
return false
, otherwise return true
, something like that: 因此,您应该做的是,如果有任何一位玩家等于0
,则返回false
,否则返回true
,例如:
for(Player i : playerList){
if (i.getNoOfGames() != 0) return false;
}
return true;
The easiest way to do it, is by using Java 8 Streams: 最简单的方法是使用Java 8 Streams:
public boolean isGameOver(){
return playerList.stream().allMatch(player -> player.getNoOfGames() == 0);
}
allMatch
will take a function that will check all the players if the number of games is 0 and return true only if all are 0. allMatch
将采用一个函数来检查所有玩家(如果游戏数为0),并且仅在全部为0时返回true。
Check the documentation for more information. 查看文档以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.