1

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.

T. Ford
  • 13
  • 3
  • 1
    You need to convert the string into an enum. https://stackoverflow.com/questions/604424/lookup-enum-by-string-value – user1717259 Jan 12 '18 at 16:53
  • 1
    notice that your RED enum doesn't equal "red" but actually "purple" and then look at how your original switch is supposed to behave. – RAZ_Muh_Taz Jan 12 '18 at 16:57

2 Answers2

4

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"));
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • 3
    This is a correct answer. However, stepping back and looking at the problem from 30,000 feet, this is a solution that uses an enum to convert from one string to another. A HashMap would probably be a better choice for that. Or have the `change()` method take an enum argument and use exclusively enums instead of strings. – DodgyCodeException Jan 12 '18 at 17:09
1

You need to add to your Enum a lookup method to return the enum by passing in a string

public static colorChange lookup(String color) {
    for (colorChange c : colorChange.values())
        if(c.getcolor().equals(color))
            return c;

    return null;
 }

Then your convert method shoould accept an Enum instead of a string:

public String convert(colorChange c) {
switch(c) {
    case RED:
        return RED.getcolor();
    case YELLOW:
        return YELLOW.getcolor();
    default:
        return c;
  }
}

And when you call the convert method you can pass in a string to the lookup method

convert(colorChange.lookup("red"))
isaace
  • 3,336
  • 1
  • 9
  • 22