Search code examples
javafor-loopenumsiterationbag

Assigning Param by Iterating Through Enum


I'm attempting to create and add some Card objects to a bag. The Card objects have enum values for their suits and ranks and I'm really trying to avoid having to create 52 unique object - one at a time. I'd like to assign the ranks by iterating through the Rank enum (Suits is also an enum) of the class like so:

for (Card.Ranks r: Card.Ranks.values())
{
    theShoe.addItem(new Card(Card.Suits.Diamonds, Card.r.values()));
    theShoe.addItem(new Card(Card.Suits.Hearts, Card.r.values()));
    theShoe.addItem(new Card(Card.Suits.Spades, Card.r.values()));
    theShoe.addItem(new Card(Card.Suits.Clubs, Card.r.values()));
}

The Card constructor looks like:

public Card(Suits s, Ranks r)
{
    suit = s;
    rank = r;
}

But it's definitely not working. Eclipse is asking me to create a field or constant "r" in the Card class. :/ Is there another way for me to do this? I've tried removing the ".values()" at the end of each line but that doesn't work either. Would really appreciate if someone could help me understand what I'm doing wrong and if I can fix it somehow. Thanks!


Solution

  • Based on your constructor, pass a Suit and a Rank. Something like,

    for (Card.Ranks r : Card.Ranks.values()) {
        for (Card.Suit s : Card.Suit.values()) { // <-- also loop over the Suits
            theShoe.addItem(new Card(s, r));
        }
    }
    

    or

    for (Card.Suit s : Card.Suit.values()) { 
        for (Card.Ranks r : Card.Ranks.values()) {
            theShoe.addItem(new Card(s, r));
        }
    }