Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate enum-instances with loop

Scenario:
I want to have an enum containing all the playing cards in a standard deck. For this example ignore the jokers.

Writing

enum Cards {
    SPADE_1(0, 1),
    SPADE_2(0, 2),
    etc.

feels wrong.

I'd like to be able to do something like this

enum Card {
    for (int suit=0; suit<4; suit++) {
        for (int face=1; face<13; face++) {
            new Card(suit, face);
        }
    }
}

I've considered defining card as a class containing suit and face fields, where suit and face are themselves enums. However in other scenarios (such as jokers having the suits red and black) this would allow for invalid card objects to be created (ie a joker of diamonds, or a red 10).

Self-answer:
Apparently I don't have enough rep to post an answer to my own question.

I'm not sure if it's considered good form to answer my own question, but @Paul just gave me a brainwave.

Declare Card to have a private constructor, and use a
    static Card getCard(suit, face)
method to validate combinations before returning them.
like image 799
Aaron J Lang Avatar asked Nov 13 '22 12:11

Aaron J Lang


1 Answers

I don't think it can be done using enum but we can implement class as enum. you can do something like below.

Implementations:

public class Card {
    private int suit;
    private int face;

    private Card(int suit, int face){
        this.suit = suit;
        this.face = face;
    }

    public int getSuit(){
        return this.suit;
    }
    public int getFace(){
        return this.face;
    }
    public static Card[] cards = new Card[52];

      static{
        int counter =0;
        for (int i=0; i<4; i++) {
            for (int j=0; j<13; j++) {
               cards[counter] = new Card(i, j);
               counter++;
            }
        }
      }
}

EDIT: set the counter of the card. Earlier it would throw NullPointerException for index more than 15.

USAGES:

System.out.println("face of the card:"+Card.cards[10].getFace());
System.out.println("suit of the card:"+Card.cards[10].getSuit());

OUTPUT:

face of the card:7
suit of the card:3
like image 66
dku.rajkumar Avatar answered Nov 16 '22 04:11

dku.rajkumar