How to use enum in switch case
34,933
Since the compiler knows what type of enum you're evaluating in the switch statement, you should drop the "qualified" portion as the error suggests (in your case: MyEnum.UserType.
) and simply use the "unqualified" enum DOCTORS
. See below:
switch(myEnum.getUserType())
{
case DOCTORS:
break;
}
Comments
-
Sree almost 4 years
I am trying to check what values are set in my VO.
Below are my clasess. I am getting "The qualified case label MyEnum.UserType.DOCTORS must be replaced with the unqualified enum constant DOCTORS"
Please help me to identify what I am doing wrong here.
MyEnum.java
public MyEnum{ private UserType userType; public UserType getUserType(){ return userType; } public void setUserType(UserType userType){ this.userType = userType; } public static enum UserType{ DOCTORS("D"), PATIENT("P"), STAFF("S"); } }
EnumTest.java
public EnumTest { ..... public void onGoBack(MyEnum myEnum) { switch(myEnum.getUserType()) { case UserType.DOCTORS: // this shows "The qualified case label MyEnum.UserType.DOCTORS must be replaced with the unqualified enum constant DOCTORS" break; } } }
-
Matt Ball over 11 yearsWas it really harder to read the error message than to post a question on SO and wait for an answer?
:/
-
HelloGoodbye almost 10 yearsWhat about if you have another constant called the same thing in another class? Wouldn't
DOCTORS
be ambiguous in that case? -
Matt Ball almost 10 years@HelloGoodbye no, it would not be ambiguous, because the compiler knows exactly which enum type the
switch
expression evaluates to. -
Justin Russo about 7 yearsMatt Ball, we're all at different levels of experience. No need to berate/belittle someone who thanked you for your help. Let's keep it professional. This user took the time to ask the question and probably just needed a little guidance about how to interpret the error message. I personally am just learning Java, and I came here because I didn't know the answer merely by the exception either.
-
Basil Bourque almost 7 yearsMatt Ball, this Question seems legitimate and sensible to me. Given that we can use
MyEnum.ABC
&MyEnum.XYZ
everywhere else in Java, I was surprised and confused to find this same syntax to be illegal in aswitch - case
.