从列表中创建一个队员队伍

时间:2011-11-25 06:07:11

标签: java linked-list

嘿我试图创建一个随机的方式从一个链表中挑选一个4人团队,我想知道这个代码是否有效。

下面是一个示例代码

 public static void enterGame(Client c) {
    int n = teamSize;
    boolean startNewGame = false;
    if(waitingPlayers.size() <= 3) {
        return; // not enough players
    }
    startNewGame = true;
    if(startNewGame) {
        System.out.println("Starting new game");
        for(int i=0; i<n; i++) {
            Collections.shuffle(waitingPlayers);
            System.out.println("Picking random player");
            waitingPlayers.remove(c);
            System.out.println("removing from random player list");
            players.add(c);
            System.out.println("adding player to ingame list");
        }
    }
}

2 个答案:

答案 0 :(得分:3)

我会使用Collections.shuffle()和子列表。为了知道你的代码是否有效,你为什么不测试它(单元测试或只是尝试一下)?

此外,这部分:

boolean startNewGame = false;
if(waitingPlayers.size() > 3) {
        startNewGame = true;
} else {
        startNewGame = false;
        return;
}
if(startNewGame) {

过于复杂,我会将其替换为:

if(waitingPlayers.size() <= 3) {
    return; // not enough players
}

完整代码:

public static void enterGame(final Client c) {      
    if(waitingPlayers.size() <= 3) {
        return; // not enough players
    }

    System.out.println("Starting new game");
    Collections.shuffle(waitingPlayers);
    System.out.println("Picking random players");
    // ? to be replaced by the real type of objects inside waitingPlayers
    final List<?> picked = waitingPlayers.subList(0, 3); 
    players.addAll(picked);
    waitingPlayers.removeAll(picked);
}

答案 1 :(得分:0)

你有一个错误 - 你正在挑选一个从0到n的数字。如果选择了n,则会出现超出范围的异常。其他可能看起来很好。