Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum in switch case

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;          }     }  } 
like image 959
Sree Avatar asked Jan 14 '13 19:01

Sree


People also ask

Can we use enums in switch-case?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

Can we use enum in switch-case in C?

We can use enums in C for multiple purposes; some of the uses of enums are: To store constant values (e.g., weekdays, months, directions, colors in a rainbow) For using flags in C. While using switch-case statements in C.

Can we use enum in switch Java?

Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum.


1 Answers

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; } 
like image 119
Matt Ball Avatar answered Sep 22 '22 02:09

Matt Ball