gpt4 book ai didi

Java For-Each 循环处理多手牌

转载 作者:行者123 更新时间:2023-12-02 02:45:37 25 4
gpt4 key购买 nike

我正在尝试找到一种将牌“发”给 4 只不同手牌的好方法。

         System.out.println("Deal to 4 Hands: "); 

Hand hand1 = new Hand();
Hand hand2 = new Hand();
Hand hand3 = new Hand();
Hand hand4 = new Hand();

hand1.addSingleCard(Deck.deal());
hand2.addSingleCard(Deck.deal());
hand3.addSingleCard(Deck.deal());
hand4.addSingleCard(Deck.deal());

hand1.addSingleCard(Deck.deal());
hand2.addSingleCard(Deck.deal());
hand3.addSingleCard(Deck.deal());
hand4.addSingleCard(Deck.deal());

System.out.println("Cards left in deck: " + Deck.size());

System.out.println("Player 1's Hand: \n" + hand1.getHand());
System.out.println("Player 2's Hand: \n" + hand2.getHand());
System.out.println("Player 3's Hand: \n" + hand3.getHand());
System.out.println("Player 4's Hand: \n" + hand4.getHand());

有没有更简单的方法来对付手?例如使用 For-Each 循环?

我尝试过这个:但它不起作用。我还没有真正使用过这种类型的循环,非常必须......

         for(Hand card : hand1){
System.out.println("Player 1's Hand: \n" + hand1);
}

顺便说一下,这会将 2 张牌发给 4 个不同的手牌,然后打印每手牌。

最佳答案

创建一个数组!

Hand[] hands = new Hand[4];

// create Hand object within the array and deal a single card to each hand
for(int i = 0; i < hands.length; i++) {
hands[i] = new Hand();
hands[i].addSingleCard(Deck.deal());
}

// deal an additional card to each hand (use a nested loop for dealing additional cards, if necessary)
for(int i = 0; i < hands.length; i++) {
hands[i].addSingleCard(Deck.deal());
}

System.out.println("Cards left in deck: " + Deck.size());

for(int i = 0; i < hands.length; i++) {
System.out.printf("Player %d's hand: \n %s\n", i+1, hands[i]);
}

该数组包含 4 个独立的 Hand 对象,并允许您通过迭代数组来对所有手执行操作。

如果每只手有四个不同的命名变量(hand1、hand2 等),则没有简单的方法可以对它们表示的对象执行操作,而无需在操作中显式使用变量名称(hand1.dealSingleCard() 等) )。

循环数组是正确的方法:)

关于Java For-Each 循环处理多手牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13388831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com