标题可能有点混乱,但我真的不知道如何解释这一点。我有一个对象列表,在本例中是位置,这些位置可以被玩家占用。如果所选位置已被占用,我如何尝试查找新位置,并继续此操作,直到找到未占用的位置?
我已经知道有20个位置,我可以手动检查每个位置,看看是否有人占用,但有没有更好的方法呢?
下面是我的代码片段。
List<Location> spawnList = arena.getManager().getRandomSpawns(); // Returns a list of possible locations
Location random = spawnList.get(new Random().nextInt(spawnList.size())); // Selects a random location from the list
if (random.isOccupied()) {
    /* Location is occupied, find another one from the list, and continue doing this until non-occupied location is found */
}抱歉,如果你不明白,我不知道一个好的方式来解释这一点。
发布于 2013-11-17 19:54:13
List<Location> spawnList = arena.getManager().getRandomSpawns();
Location random;
Random r = new Random();
do {
  random = spawnList.get(r.nextInt(spawnList.size()))
} while(random.isOccupied());如果所有的位置都被占用,这将失败,你应该在之前检查这一点。
发布于 2013-11-17 19:55:12
您可以选择以下两种方式之一:
发布于 2013-11-17 19:58:02
您可以声明一个标志来检查是否找到候选位置,并使用while - loop生成随机位置,例如,
    Location random = null;
boolean foundLocation = false;
while(!foundLocation)
{
    random = spawnList.get(new Random().nextInt(spawnList.size()));
    if(!random.isOccupied())
    {
        foundLocation = true;
    }
}注意:这里的假设位置列表中至少有一个位置没有被占用。如果所有的位置都被占用了。那么上面的代码就无法使用了。它将在无限循环中。我们最好先检查一下列表中是否至少有一个位置没有被占用。
https://stackoverflow.com/questions/20030317
复制相似问题