gpt4 book ai didi

java - 创建两副相同但不同的牌,并同时从中抽取

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

我正在利用标准数组驱动的方法来创建、洗牌和绘制一副 52 张标准扑克牌。我的挑战是同时并排绘制两张相同但不同的牌组。

最初我认为在可执行的 DeckDrawTest 类中拥有 Deck 类的两个实例就足够了,但是当我要求该类绘制 104 (52 x 2) 次时,我得到了一副牌的所有 52 张牌和 52 张空牌条目。然后,我创建了一个名为 Deck2 的重复 Deck 类,并更改了所有方法和变量名称,同时保持功能相同 - 没有骰子,相同的结果。然后,我尝试通过复制 Deck 和 Deck2 所源自的 Card 类来克服潜在的多重继承问题,使另一个类与 Card 相同,称为 Card2,但具有不同的变量名称。并没有改变结果。代码如下。

卡片

public class Card
{
private final String name;

private final String suit;

public Card(String cardName, String cardSuit) {
this.name = cardName;
this.suit = cardSuit;
}

public String toString() {
return name + "of " + suit;
}

}

Deck2(目前从 Card 中提取,一旦我得到它的功能,将修复名称):

public class Deck2
{
private static final SecureRandom randomClam = new SecureRandom();
private static final int DECKSIZE2 = 52;

private Card[] deck = new Card[DECKSIZE2];
private int currentCard = 0;

public Deck2() {
String[] names2 = {"A ", "2 ", "3 ","4 ", "5 ", "6 ", "7 ", "8 ", "9 ", "10 ", "J ", "Q ", "K "};
String[] suits2 = {"♠ ", "♥ ", "♣ ", "♦ "};

for (int count = 0; count < deck.length; count ++) {
deck[count] =
new Card(names2[count % 13], suits2[count /13]);
}

}

public void shuffle2() {
currentCard = 0;

for (int first2 = 0; first2 < deck.length; first2++) {
int second2 = randomClam.nextInt(DECKSIZE2);

Card temp2 = deck[first2];
deck[first2] = deck[second2];
deck[second2] = temp2;
}

}

public Card dealCard(){
if (currentCard < deck.length) {
return deck[currentCard++];
}
else {
return null;
}
}
}

DeckDrawTest(从 DeckDeck2 绘制)

public class DeckDrawTest
{
public static void main(String[] args) {
Deck myDeck = new Deck();
myDeck.shuffle();
Deck2 yourDeck = new Deck2();
yourDeck.shuffle2();

for(int i = 1; i <=104; i++){
System.out.printf("%-20s", myDeck.dealCard(), "%-20s", yourDeck.dealCard());
if(i %2 == 0) {
System.out.println();
System.out.println();
}

}

}
}

那么我如何让这个程序从两个不同但相同的牌组中进行绘制,而不是仅从一个牌组中进行绘制?

最佳答案

你的变量i上升到104,但在每个循环中你在两副牌上调用dealCard。这就是 null 值的来源。你只需要循环到52:

for (int i = 1; i <=52; i++) {

您使用 printf 的输出是错误的,该函数只需要一个格式化程序。您的版本仅输出 myDeck.dealCard() 的值,并调用(但不使用)yourDeck.dealCard()。要创建包含两个调用的输出的行,请使用如下内容:

 System.out.printf("%-20s %-20s", myDeck.dealCard(), yourDeck.dealCard());

关于java - 创建两副相同但不同的牌,并同时从中抽取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654594/

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