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
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!");
}
}
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With