Search code examples
javaenumsswitch-statementenumerate

how to check enum values and return corresponding enum


my schema is as below

"statusCode": {  
            "type": "string",
            "enum": ["A", "T", "U"]
        }

I am trying to write a method which would check for the code and return corresponding enum.

private void updateStatusCode(Event event) {
        Enum code = null;
        switch(event.getStatusCode()) {
            case A:
            code = ["A"];
            break;
            case T:
            break;
            case U:
            break;
            default:

        }
         return code;

    }

event.getStatusCode valid values are: A , T , U. Now I need to check for these codes and return enum based on the codes. I tried the above but it gives me error on code = ["A"]. error states below.

Syntax error on token "=", Expression expected after this token

How do i fix this ? I am new to java. any help is appreciated, Thanks


Solution

  • I don't know what you are trying to do here but you misunderstood the concept of enum. In the comment you said statusCode is an enum but it isn't an enum it's in a json format and not a real Java expression.As I said I don't know what you are trying to achieve but you can modify your code like below .

    first create an enum

    enum StatusCode{
       A,
       B,
       U
    
    }
    

    if you want to get the string equivalent of the enum values you use the following code

    enum StatusCode{
       A("A"),
       T("T"),
       U("U");
       String code;
       public StatusCode(String code){
         this.code=code;
       }
       String getCode(){
         return code;
       }
      }
    
    

    and then modify your method like this

    private void updateStatusCode(Event event) {
            StatusCode code;
            switch(event.getStatusCode()) {
                case A:
                code = StatusCode.A;
                break;
                case T:
                code = StatusCode.T;
                break;
                case U:
                code = StatusCode.U;
                break;
            }
             return code;
    
        }
    

    you can get the string value of an enum as

    StatusCode code=StatusCode.A;
    String strCode=code.getCode();