Newbie here. I want to convert the switch statement to use enum. I created enum, used that in switch statement but then i can't figure out how to pass in c
into that to return appropriate value.
Method to convert:
public String convert(String c) {
switch(c) {
case "red":
return "purple";
case "yellow":
return "orange";
default:
return c;
}
}
Enum that I tried and didn't work:
public enum colorChange {
RED("purple"),
YELLOW("orange");
private final String color;
private colorChange(String color) {
this.color = color;
}
public String getcolor() {
return color;
Ultimately, what i am looking to do is something like this:
public String convert(String c) {
switch(c) {
case RED:
return RED.getcolor();
case YELLOW:
return YELLOW.getcolor();
default:
return c;
}
}
Many thanks in advance for help.
Something like this is the tidiest way to do it - you don't even need a switch
.
public enum ColorChange {
RED("purple"),
YELLOW("orange");
private final String color;
ColorChange(String color) {
this.color = color;
}
public static String change(String color) {
return valueOf(color.toUpperCase()).color;
}
}
public void test(String[] args) {
System.out.println("red -> "+ColorChange.change("red"));
}