1
votes

I am stuck on what feels like a seemingly simple question.

Say I have the following enum:

   enum CARDS {

        JOKER(1),
        JACK(2),
        QUEEN(3),
        KING(4),
        ACE(5)
        ;

        private final int cardNumber;

        CARDS(int cardNumber) {

            this.cardNumber = cardNumber;

        }

    }

I would like to find a way to determine the value of an enum (JOKER, JACK, QUEEN, KING, ACE) using an integer that is randomly generated from a separate class. Would this be possible, and is this good practice?

For example:

I have an integer, say, 3.

I would like to match the integer to the constant value assigned to the enum, in this case my integer 3 would result in being paired to queen.

1
As the answer below pointed out, enums are automatically stored in an array, so you don't need the cardNumber field unless you were planning on using it for something else. - qwerty

1 Answers

3
votes

It's as simple as:

int integer = 3;

CARDS card = CARDS.values()[integer - 1];

Note: This works because QUEEN's ordinal is 2 (zero-based).

Use CARDS.valueOf(String) to convert an enum name to CARDS member.

As far as good practice, I suggest a design that takes advantage of the ordinal for ordering and random selection and if you need rank or strength, make those separate attributes (as you did).

You might select a random member with:

CARDS[] deck = CARDS.values();
Random random = new Random();

CARDS card = deck[random.nextInt(deck.length)];

without relying on any specific ordinal value.