Java - 如何从 Arraylist 中获取一个元素并插入到另一个数组中?

Java - how to get an element from Arraylist and insert into another Array?

此时我很困惑。 我正在制作纸牌游戏,但不知道如何编写 "deal" 方法。 "deal" 方法向 Player 数组中的每个玩家发一定数量的牌。 我的牌组 class 包含一个 ArrayList,如下所示:

public ArrayList<WarCard> cardStack = new ArrayList<WarCard>();

而且我已经向 cardStack 添加了 52 张预制卡片。 我的播放器数组有两个元素,播放器 1 和播放器 2 ... 我的问题是,如何将 cardStack 中的 52 张牌分配给玩家 1 或玩家 2? 我不知道从哪里开始... 这是我目前所拥有的:

public void deal(WarPlayer[] players, int numberOfCards){
    //whats the "certain number"? - suppose each one gets 26 cards - 1/2 of     the total cards
    numberOfCards=26;//26 cards go to each player
    for(int i=0;i<26;i++){
    players[i]=cardStack.get(i);
    }

}

并且此代码块无法正常工作...如预期的那样。 感谢您的帮助!

您可以编写如下代码:

    // let's say you have a cardStack containing 52 cards
    ArrayList<String> cardStack = new ArrayList<String>();

    //you can shuffle the cards before dealing
    shuffle(cardStack);

    String[] players = new String[]{"player1", "player2"};

    //this is the loop to deal cards to all players in the array
    for (int i = 0; i < players.length; i++) {

        // if you need to deal 10 cards to each player
        for (int j = 0; j < 10; j++) {
            players[i].addCard(cardStack.get(0));   // assuming your Player Object has an addCard method

            // you will need to remove the card from the cardStack since you gave it to the player
            cardStack.remove(0);                    
        }

    } 

在向每位玩家发了 10 张牌(对于本例)后,列表将剩下 32 张牌,每位玩家将有 List 10 张牌。

希望对您有所帮助

编辑: 编辑 player[i].addCard(cardStack.get(j)); 以确保玩家拿到牌组中的第一张牌。应该是:

player[i].addCard(cardStack.get(0));