循环的Java逻辑//试图创建一个卡片组

时间:2013-03-20 17:00:02

标签: java arrays object loops

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

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

Card.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;
    }
}

2 个答案:

答案 0 :(得分:6)

问题在于:

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

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

更改代码,只使用前2个for-loop s

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

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

答案 1 :(得分:1)

对于每个套件和价值,您将遍历所有52张牌并将其设置为适合和价值。由于最后的套装/价值对是DIAMOND和ACE,所以这些卡最终都会结束。

如果你使用π摆脱循环,而只是做:

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

然后我认为这应该有用。