+ 2
(JAVA)How do I get an Enum object using a string?
I have the following code: enum Operators { ADDITION("+"), SUBTRACTION("-"), MULTIPLICATION("*"), DIVISION("/"), REMAINDER("%"), INCREMENT("++"), DECREMENT("--"); private String ope1; Operators(String p) { this.ope1=p; } public String ope1() { return ope1; } } For instance, if a user enter the string "+", using this string I should get the ADDITION enum. Why I cannot get the enum using the following line: Operators p1 = new Operators ("+"); -> This is a mistake..I am learning. How should I do it correctly?.. P.D: I need to get the enum to properly use a switch statement. I need a STRING TO ENUM mapping
3 odpowiedzi
+ 2
I meddled with this topic a bit, and I came up with a way (I hope it solves your issue).
I added a static method to the enum, which returns the correct enum label based on the string value of the operator.
https://code.sololearn.com/cHUFEsUPB7oW/?ref=app
+ 2
I have an even better one that does not rely on the static method. Just looping through all enum elements, and if the operator string is matching then the enum is assigned.
https://code.sololearn.com/cm1mIbEpG4d5/?ref=app