I would like to know if there is a way to do the following:
Here is a simple Switch, but I am basically hardcoding the switch argument.
enum Color{red,green,blue}
class SwitchEnum{
publicstaticvoid main(String[] args){
Color c = Color.green;
switch(c){
case red: System.out.println(“red”);
break;
case green: System.out.println(“green”);
break;
case blue: System.out.println(“blue”);
break;
default: System.out.println(“not found”);
}
}
}
I want to be able to assign it based on user input. If I am restricted to assigning the Color value, then I will need to have an if/else contruct to decide which enum variable to populate like such:
if (cmd.equals("green"))
Color c = Color.green;
Else if(cmd.equals(“red”))
Color c = Color.red;
Etc…
now process the switch statement.
I would MUCH rather have the ability to do something like:
String input = “green”;
Color c = (Color)input;
now process the switch statement
is there anyway to do this without having to have the if else to do the decision making process and I can do it on the fly with cleaner code?
2. You can't convert a String to a enum value. Do this instead:
privatestatic Color getColor(String inputString) {
Color inputColor = null;
for (Color col : Color.values()) {
if (col.toString().equalsIgnoreCase(inputString)) {
inputColor = col;
}
return inputColor;
}
Note: I used differnt names on purpose, so it is easier to understand.