Search code examples
javaarraysenumsplaying-cards

Enum types may not be instantiated error


I am making a basic card deck at the moment and I've encountered a problem using enums.

How do I fix the following error(enum types may not be instantiated) in my code and get the value assigned to each enum

 public enum Rank {

    ACE(14),
    KING(13),
    QUEEN(12),
    JACK(11),
    TEN(10),
    NINE(9),
    EIGHT(8),
    SEVEN(7),
    SIX(6),
    FIVE(5),
    FOUR(4),
    THREE(3),
    TWO(2);
    private final int rankValue;

    Rank(int rankValue) {
        this.rankValue = rankValue;
    }

    public int getRankValue() {
        return rankValue;
    }

}
private Card[] cards = new Card[52];

public Deck() {
    int posInDeck = 0;
    for (Suit s : Suit.values()) {
        for (Rank r : Rank.values()) {
            cards[posInDeck] = new Card(s.toString(),new Rank(r.getRankValue(), r.toString()), false);// ERROR HERE
            posInDeck++;
        }
    }
}

Solution

  • You can't instantiate an enum like you would instantiate a class. The statement new Rank(r.getRankValue(), r.toString()) is incorrect.

    This is what you can do instead :

    cards[posInDeck] = new Card(s.toString(),r,false);