So I’m coding Blackjack in Java and I’ve stored my suit and rank values in enums
public enum Suit
{
spades, hearts, clubs, diamonds
}
public enum Rank
{
two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace
}
I have a Deck class which keeps a Stack of ‘Cards’.
Cards contain fields for Suit and Rank.
public class Card
{
static Suit suit;
static Rank rank;
Card(Suit suit, Rank rank)
{
this.suit = suit;
this.rank = rank;
}
public String toString()
{
return rank + " of " + suit;
}
//getters and setters ommitted
}
The constructor in Deck should be iterating through each each suit and rank and passing these on as parameters to create a deck of 52 cards, but it seems to be stuck on the last values of each and I end up with 52 ‘aces of clubs’. I don’t understand why, as the suit and rank seem to print correctly, it just seems to be when they’re passed as a parameter to add() that they misbehave.
public class Deck
{
static Stack<Card> d = new Stack<Card>();
Deck()
{
if (!d.isEmpty())
{
clear(); //Empties the stack if constructor is called again
}
for (Suit suit : Suit.values())
{
for (Rank rank : Rank.values())
{
//System.out.println(suit + " " + rank);
//This seems to print the right values
add(new Card(suit, rank)); //These are stuck on 'clubs' and 'ace'
}
}
System.out.println(d);
shuffle(); //Method which shuffles the deck
}
public static void add(Card c)
{
d.addElement(c);
}
//shuffle(), clear() and other methods omitted
}
The full project can be seen on github, if that helps.
Your suit and rank fields in Card should not be static!
Neither should your Deck fields!
Static fields are per-class, so your Card constructor is overwriting the same value every time it’s called.