(JAVA)How do I get an Enum object using a string? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

27th Apr 2019, 1:37 AM
Rosana Rodríguez Milanés
Rosana Rodríguez Milanés - avatar
2 Answers
+ 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
27th Apr 2019, 4:30 AM
Tibor Santa
Tibor Santa - avatar
+ 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
27th Apr 2019, 4:53 AM
Tibor Santa
Tibor Santa - avatar