1

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.

robertmotr
  • 39
  • 1
  • 3
  • 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 Aug 13 '20 at 23:40

1 Answers1

3

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.

Allen D. Ball
  • 1,916
  • 1
  • 9
  • 16
  • 4
    This will work, but see [Is it good practice to use ordinal of enum?](https://stackoverflow.com/questions/44654291/is-it-good-practice-to-use-ordinal-of-enum) – dnault Aug 13 '20 at 23:46
  • 2
    I think my recommendation aligns with top answers of that post. I'll add to my answer a specific example for choosing a random member. – Allen D. Ball Aug 13 '20 at 23:54
  • 2
    @dnault, in this case it is a good practice, because the OP wants to use the ordinal for randomly selecting an enum value (maybe for a "deck shuffling" method). The problem with using ordinals is that sooner or later the values in an enum class will be rearranged - either by accident, or someone wanted to have them alphabetically sorted, or they simply inserted a new value in the middle.If you use the ordinal value for some crude business logic in a totally different class, such reorderings will break your code. If you just want a random value, then the reordered enums will be just as random. – Mike Aug 14 '20 at 00:02
  • 3
    It may be appropriate to create a static method in the enum and put this logic there. – Slaw Aug 14 '20 at 00:15