一尘不染

如何编写初始化52个卡对象的构造函数

java

这是我需要做的:

该构造函数使用52个卡对象初始化Deck,该对象表示标准卡座中的52张卡。这些卡片必须从黑桃A到钻石之王订购。

这是我的尝试:

private Card[] cards;
String suit, card;
private final int DECK_SIZE = 52;

public Deck() 
{
    cards = new Card[DECK_SIZE];
    String suit[] = {"spades", "hearts", "clovers", "diamonds"};
    String card[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Joker", "Queen", "King"};
    for (int c = 0; c<13; c++)
        for (int s = 0; s<4; s++)
        {
            cards.equals(new Card(suit, card));

        }



}

这部分给我一个错误:“((新卡(套装,卡));” 说构造函数Card(String [],String
[])是未定义的。我不确定是否允许我们添加额外的构造函数。为我们编写的代码确实包含Card(int,int)。

好吧,那呢?这行得通吗?

public class Deck {

    private Card[] cards;
    int value, suit;
    private final int DECK_SIZE = 52;

    public Deck() 
    {
        //1 = Ace, 11=joker, 12=queen, 13=king
        //1 = spades, 2 = hearts, 3 = clovers, 4 =diamonds
        cards = new Card[DECK_SIZE];
        int suit[] = {1, 2, 3, 4};
        int card[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        for (int c = 0; c<13; c++)
            for (int s = 0; s<4; s++)
            {
                cards.equals(new Card(suit[s], card[c]));

            }

        }

阅读 213

收藏
2020-12-03

共1个答案

一尘不染

可能是这样的:

cards = new Card[DECK_SIZE];
String suits[] = {"spades", "hearts", "clovers", "diamonds"};
String cards[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Joker", "Queen", "King"};

int cardIndex = 0;
for (String suit : suits) {
    for (String card : cards) {
        cards[cardIndex] = new Card(suit, card);
        cardIndex++;
    }
}
2020-12-03