-1
public enum Suit
{
    CLUBS,
    HEARTS,
    SPADES,
    DIAMONDS 
}

public enum Value
{
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT,
    NINE,
    TEN,
    JACK,
    QUEEN,
    KING,
    ACE
}

卡片.java

public class Card {

    private Suit suit;
    private Value value;

    public Card(Suit theSuit, Value theValue)
    {
        suit = theSuit;
        value = theValue;
    }

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

    public Value getValue()
    {
        return value;
    }

    public Suit getSuit()
    {
        return suit;
    }

    public boolean equals(Card other)
    {
        if (value.ordinal() == other.value.ordinal()
                || suit.ordinal() == other.suit.ordinal())
        {
            return true;
        }
        else {
            return false;
        }
    }

}

CardPile.java

public class CardPile

{
    public Card[] cards;

    private int numCards;

    public CardPile()
    {
        this.cards = new Card[52];
        this.numCards = 0;

        // The problem is here, when I try to iterate through the enums and the
        // array to populate my cards[] of 52 objects Card it populates it with
        // 52 Card which are all ACE of DIAMONDS, it looks like the triple loops
        // populates 52 times the two last elements of my enum, but I can't
        // figure out how to fix that! Thanks in advance!

        for (Suit s : Suit.values())
        {
            for (Value v : Value.values())
            {
                for (int π = 0; π < cards.length; π++)
                {
                    cards[π] = new Card(s, v);
                }
            }
        }
    }

    public boolean isEmpty()
    {
        for (int i = 0; i < cards.length; i++)
        {
            if (cards[i] != null)
            {
                return false;
            }
        }
        return true;
    }

    public int getNumCards()
    {
        return numCards;
    }
}
4

2 回答 2

6

问题在这里:

for (int π = 0; π < cards.length; π++) {
    cards[π] = new Card(s, v);
}

您使用相同的sv变量来创建Card实例并将其分配给cards数组中的所有元素,替换每个 (s, v) 对组合上的每个值。

更改代码以便仅使用前 2for-loop秒来填充它:

int count = 0;
for (Suit s : Suit.values()) {
    for (Value v : Value.values()) {
        if (count < cards.length) {
            cards[count++] = new Card(s, v);
        }
    }
}

顺便说一句,您不应该将名称用作π变量,并确保缩进您的代码。

于 2013-03-20T17:04:11.403 回答
1

对于每个套件和价值,您迭代所有 52 张牌并将它们设置为该套件和价值。由于最后一个花色/价值对是 DIAMOND 和 ACE,这就是所有牌的最终结果。

如果您使用 π 摆脱循环,而只需执行以下操作:

int counter = 0;
for (Suit s : Suit.values())
{
    for (Value v : Value.values())
    {
        cards[counter++] = new Card(s, v);
    }
}

然后我认为这应该有效。

于 2013-03-20T17:07:51.560 回答