Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using enum inside a switch

Tags:

java

enums

Can we use enum inside a switch?

public enum Color {
  RED,BLUE,YELLOW


}


 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}

I am getting some error in this.

The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem
like image 505
ako Avatar asked Dec 05 '22 22:12

ako


2 Answers

case COLOR.BLUE:

    }

In the above code instead of COLOR.BLUE only write BLUE


E.G.

import java.awt.Color;

class ColorEnum {

    enum Color{BLUE,RED,YELLOW};

    public static void main(String[] args) {
        Color c = Color.BLUE;
        switch(c) {
            case BLUE:
                System.out.println("Blue!");
                break;
            case RED:
                System.out.println("Red!");
                break;
            case YELLOW:
                System.out.println("Yellow!");
                break;
            default:
                System.out.println("Logic error!");
        }
    }
}
like image 63
Ankit Avatar answered Dec 07 '22 12:12

Ankit


Write it like this:

public void test(){
  switch(c) {
  case BLUE:

  }
}

The enum label MUST NOT be qualified when used as a case label. The grammar at JLS 14.11 says this:

SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

EnumConstantName:
    Identifier

Note that a simple identifier is require, not an identifier qualified by the enum name.

(I don't know why they designed the syntax like that. Possibility it was to avoid some ambiguity in the grammar. But either way, that's the way it is.)

like image 34
Stephen C Avatar answered Dec 07 '22 11:12

Stephen C