How to pass variable by parameter created in enum in Java?

1

I created a class enum of java

public enum Cor {
    AZUL(1),VERMELHO(2),VERDE(3);
    private int var;
     Cor(int var)
    {
    this.var = var;
    }
}

In main I will create a menu using do/while and switch/case and will be shown the colors, how to pick the chosen color and pass in the parameter of a method?

In the menu it goes like this

                System.err.println("Escolha uma cor");
                System.err.println("1-Azul");
                System.err.println("2-Vermelho");
                System.err.println("3-Verde");

When typing 1, you should get the color Blue.

    
asked by anonymous 09.03.2016 / 19:03

2 answers

2

Here are two examples:

Switch To use switch you need to create constants with their values:

public static final int AZUL= 1;
public static final int VERMELHO= 2;
public static final int VERDE= 3;

public static Cor selecaoPorSwitch(int selecao){
    Cor cor= null;
    switch (selecao) {
    case AZUL:
        cor = Cor.AZUL;
        break;
    case VERMELHO:
        cor = Cor.VERMELHO;
        break;
    case VERDE:
        cor = Cor.VERDE;
        break;
    }
     return cor;
}

if / else

Simple comparison of value with selection. For this it is necessary to create getVar() to have access to the value of each enum :

public static Cor selecaoPorIf(int selecao){
    Cor cor = null;
    if(selecao == Cor.AZUL.getVar()){
        cor = Cor.AZUL;
    }else if(selecao == Cor.VERDE.getVar()){
        cor = Cor.VERDE;
    }else if(selecao == Cor.VERMELHO.getVar()){
        cor = Cor.VERMELHO;
    }
    return cor;
}

How to test:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Selecione uma cor: \n 1-Azul\n2-Vermelho\n3-verde \n :");
    int selecao = scan.nextInt();
    Cor cor = selecaoPorIf(selecao);
    System.out.println("selecaoPorIf : "+cor);

    cor = selecaoPorSwitch(selecao);
    System.out.println("selecaoPorSwitch : "+cor);
}
    
09.03.2016 / 20:21
3

From what I understand you would like to make a menu of the type:

  • BLUE
  • RED
  • GREEN
  • If so, you can do the following. To display the menu:

    for(Cor cor : Cor.values()) { System.out.println(cor.getIndice() + ". " + cor.name()); }

    To select the color, the user can enter an index. This way you can add the following method in the enum:

    public static Cor fromIndice(int indice){
        for(Cor cor : Cor.values()) {
            System.out.println(cor.getIndice() + "-" + cor.name());
        }
        throw new IllegalArgumentException("Indice invalido");
    }
    

    When receiving an index returns a color.

    If not, add more information.

        
    09.03.2016 / 19:56