嘿,我试图创建一个随机的方式来选择一个团队4从linkedlist和我想知道如果这个代码将工作。
这里有一个示例代码
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");
}
}
}
我将使用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);
}
您有一个错误-您正在从0到n中选择一个数字。如果选择了n,您将得到一个越界异常。