-1

I am doing a Hearthstone text game in Java and I'm kinda stuck at choosing the Hero/Rank for the player[x]. I have a Hero class, which contains a Rank enum {MAGE, PALADIN, PRIEST, etc...}, and I have a Game class which has access of the Rank enum with Hero.Rank.VALUE. Also, and this is the important one, I have a TextView class that requests the user to choose the hero class with an int. Thing is, that an int cannot be converted to Rank, and I would like to know an appropriate way to set the player Rank by user input.

I'm using an MVC structure, so it is important to do the Hero Rank request at TextView.

takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • Do you know about `switch` statements? If those wouldn't work, check out the docs for the `Enum` interface (I think?) and see if any of those methods apply. – Nic Nov 24 '15 at 00:01
  • Yeah, actually I didn't try that because in Java, Enum is an object of his own kind, so I discarded the switch possibility. Actually I resolved it a few hours ago, what I did was to convert the Enum to an array using the Enum values() method, which returns you an array of the Enum elements, then there was where I used the switch, giving the index as parameter, and so achieving that the user could control the enum element choice. – LifGwaethrakindo Nov 25 '15 at 01:38
  • So... you took my second suggestion and looked at the docs? (And for the record, `switch`es work with `Enum`s. Try it and see :D) – Nic Nov 25 '15 at 01:39
  • well, yeah, but not as an int, I made before a switch in a method that took as parameter the Enum, then switched through the Enum, but checked the cases as the values I gave it when I created it (ex. method(Card.Rank classEnum)...switch(classEnum)...case MAGE:...break;...) – LifGwaethrakindo Nov 25 '15 at 01:49

1 Answers1

0

One possibility is to use an enum with a parameter. The parameter would be the associated int returned from the user.

enum Rank {
    MAGE(0), PALADIN(1), PRIEST(2), ...;

    private int value;

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

    int getValue() {
        return this.value;
    }
}

You could then find the correct enum case by iterating over Rank.values() and checking, if the value matches with the int given by the user. Or you can use a Hashtable to lookup the enum keys by their value, which is described in this article

Another more simple approach would be to use the ordinal() method of an enum, which is described in this answer, but this approach does not work, if the values of an enum do not match their ordinal.

Community
  • 1
  • 1
Palle
  • 11,511
  • 2
  • 40
  • 61
  • Yeah, actually I've tried with the values() method and it worked the way I wanted, just giving an int as parameter and so getting the index of the array. – LifGwaethrakindo Nov 25 '15 at 01:39