JAVA:找不到函数中使用的数组元素?

时间:2013-12-06 08:14:09

标签: java arrays arraylist

在我的Undead课程中,我编写了一个方法,允许不死生物角色牺牲自己,并在剩余的两个队友之间分配剩余的生命值(角色阵列中的玩家总数总是3)。

我的功能是

public void sacrifice(Character other1, Character other2){
    int healthgiven = health/2; 
    health -= health;
    other1.health += healthgiven; 
    other2.health += healthgiven;
    System.out.println(name + " has sacrified himself for the team. 
    His health has been distributed among the two remaining allies. ");
}   

据我所知,这是有效的,但当我必须在主要使用它时它就成了一个问题。我不得不弄清楚列表中的哪些元素是另外两个角色(谁也可以是亡灵)。基本上当我最终调用undeadchar.sacrifice(other1,other2)时,我需要找到两个不是undeadchar的字符。对不起,如果它令人困惑,我会在必要时重写它。

3 个答案:

答案 0 :(得分:0)

使用Java 8:

List<Character> charList = ... 
Character sacrificeChar = ...
List<Character> notSacrificeList = charList.stream()
                                        .filter(x -> !x.equals(sacrificeChar))
                                        .map(Character::new)
                                        .collect(Collectors.toList());

答案 1 :(得分:0)

假设你有类似的东西:

ArrayList<Character> chars = ...; // all of them
Character sacrificingChar = ...; // the one that will sacrifice himself

然后你可以这样做:

List<Character> others = new ArrayList<>(chars);
others.remove(sacrificingChar);
sacrificingChar.sacrifice(others.get(0), others.get(1));

答案 2 :(得分:0)

我认为你应该在调用方法sacrifice之前进行检查 假设你getHealth()中有Player个功能,一旦玩家牺牲了健康,玩家的健康状况为0,那么,

List<Player> PlayersList = new ArrayList<Player>();
Player sacrificingPlayer = ... //Your logic to find sacrificing player
List<Player> healthyPlayers = GetHealthyPlayer(PlayersList );
sacrificingPlayer.sacrifice(healthyPlayers.get(0), healthyPlayers.get(1));

和功能GetHealthyPlayer();

public List<Player> GetHealthyPlayer(List<Player> PlayersList )
{
  List<Player> Players = new ArrayList<Player>();
  int PlayerCount = 0;
  for (Player pl: PlayersList )
  {
      if(pl.getHealth() > 0)
      { 
         Players.add(pl);
         PlayerCount++;
         if(PlayerCount == 2) //Since we need only two healthy player
             break;
       }
  }
  if(PlayerCount != 2) 
      throw Exception("Two healthy players not found "); //Or you Can return null and check
  return Players;
}