2
votes

I am trying to use two enums to create a deck of cards via a 2d array, then print all of the created cards.

public class Deck {

private Card[][] cards;

public Deck() {
  cards = new Card[4][13];
  for (Card.Suit suit : Card.Suit.values()) {
     for (Card.Rank rank : Card.Rank.values()) {
        //This is where my problem begins
        cards[suit][rank] = new Card(suit, rank);
     }
  }
}



public Card getCard(Card.Suit s, Card.Rank r) {
   //The error appears here as well.
   return cards[suit][rank];
}

Here are the enums I'm trying to use.

public class Card {
   private Rank rank;
   private Suit suit;

   // Kinds of suits
   public enum Suit {
      CLUBS,
      DIAMONDS,
      HEARTS,
      SPADES;
   }

   // Kinds of ranks
   public enum Rank {
      ACE,
      DEUCE,
      THREE,
      FOUR,
      FIVE,
      SIX,
      SEVEN,
      EIGHT,
      NINE,
      TEN,
      JACK,
      QUEEN,
      KING;
   }

   public Card(Suit s, Rank r) {
      rank = r;
      suit = s;
   }
...}

What I think should be happening is that the for loop is going through each element via Card.Suit.values() and then Card.Rank.values() and creating a new Card(Suit suit, Rank rank), according to it's index in the array cards[s][r].

When I compile my code it gives the error.

"Deck.java:42: error: incompatible types: Suit cannot be converted to int

cards[suit][rank] = new Card(suit, rank);"

1
Yes, indices of an array are integers, starting from 0. Not suits or ranks. That's what the error tells you. docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.htmlJB Nizet
suit is an object of an enum, not an integer. you have to fetch your desired enum value from suit object and apply ordinal method so that you can get the index as an integer value.huk
Thanks very much for your help, the .ordinal() suggestion works perfectly!Meekswel

1 Answers

2
votes

Indexes in arrays need to be integers, but at line cards[suit][rank] = ... you are passing enum constant held by suit (like CLUBS) and rank. You can get int representing position of current enum constant with Enum#ordinal() method.

Change your

cards[suit][rank] = new Card(suit, rank);

to

cards[suit.ordinal()][rank.ordinal()] = new Card(suit, rank);
//        ^^^^^^^^^^      ^^^^^^^^^^