Home > Software engineering >  how to check enum values and return corresponding enum
how to check enum values and return corresponding enum

Time:04-26

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

CodePudding user response:

You seem confused about how enumerations works in Java. An enum is basically a list of well-known values that can be assigned to an instance of the enum class. It encompasses the methods to convert from/to String as frequently required. Enum is the superclass of them all, but you usually don't need to use it directly.

For instance, let's say I've got the following definition:

enum StatusCode {
 A,
 T,
 U
}

This means that an object of the class StatusCode can only have the values A, T or U. And to convert, I'd use :

String fromString = "A";
StatusCode sc = StatusCode.valueOf(fromString); //gives sc = StatusCode.A
String backToString = sc.name(); //gives backToString = "A"

Learn more here: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

CodePudding user response:

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();

  • Related