user3579225 user3579225 - 8 days ago 8
Java Question

Building a deck of cards in java using 2 different ENUMS

I have a lab for class (we are allowed to seek outside help) creating klondike solitaire. I am a total noob when it comes to programming (this is my first ever class in programming). We just learned about enums, and I have to build a deck using them (I've reviewed other questions about this, but I haven't found a solution that matches what I need yet). We have two enums (rank and suit):

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


and

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


Now, I need to combine them into an array called Deck, which stands as such:

public Deck() {
cards = new Card[52];
}


To put the cards into the deck, I've been trying to use the ".values" but I can't get it right. There is a testing code with this lab and it says I'm not getting any of the points for this. What am I doing wrong?

public void fill() {
for (int i = 0; i<52;i++){
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
cards[i]= new Card(r,s);
}
}
}
}


Any help is much appreciated. Thanks!

Answer

You state,

Now, I need to combine them into an array called Deck, which stands as such:

No, you need to create a class Card that has one field of each of the enums. Only after doing that can you create a Deck of your Cards. So do that -- create a Card class, give it at least two fields, one for each enum, plus an appropriate constructor, plus getters, plus a decent toString() and then you're set.

Also, this is wrong:

public void fill() {
    for (int i = 0; i<52;i++){ // get rid of this loop
    for (Suit s : Suit.values()) {
    for (Rank r : Rank.values()) {
        cards[i]= new Card(r,s);
}

The code above will try to stuff 52 cards into each index spot. For instance, it will try to stuff all 52 cards into the cards[0] spot, same for the cards[1] item, and only the last Card will be added. You'll have an array of 52 King of Diamonds -- not what you want.

Instead, get rid of the outer loop, and instead increment the i inside your loop:

public void fill() {
  int i = 0;
  for (Suit s : Suit.values()) {
    for (Rank r : Rank.values()) {
      cards[i]= new Card(r,s);
      i++;  // increment i here
    }
  }
}