0

I have an Enum file with a few values in Java. In my main program, I have a function that receives an integer as parameter and I have to perform different actions depending on that value, which is the same as the number that the enum elements have.

I'm doing the following:

public String operation(int option, int chosenBox){
    String result = "";

    switch(option){
        case 0:
            model.startGame(this.playersName);
            result = "...";
            break;
        case 1:
            model.play();
            result = "...";
            break;

I need to change the cases' options to point to the elements of the enum instead of the numbers, because sometime I'll need to add an element into the enum and I'd eventually need to change all numbers.

The enum is called MenuOption, and I've tried to do this:

case OpcionMenu.PLAY.ordinal(): // This is for case 0

But the following error appears: "constant expression required".

d3vcho
  • 85
  • 7

1 Answers1

2

You don't need the position at all, you can just switch over the enum directly.

public String operation(Option option, int chosenBox) {
    switch(option) { // ...
}

If you insist on passing an int to the method, you can do

public String operation(int optionIndex, int chosenBox) {
    Option option = Option.values()[optionIndex];
    switch(option) { // ...
}
daniu
  • 14,137
  • 4
  • 32
  • 53
  • Thank you! It worked. It's mandatory for me to pass an integer so, that's why I was asking. – d3vcho Dec 13 '18 at 11:39