2

I have this enum : public enum Color { RED, YELLOW; }. And I want to create a method that returns the opposite color of the actual one. So if I have RED, my method returns YELLOW. But I don't know the process to follow to do that. First step : public Color opposite() { return ??? }

2
  • Do you know how to write an if statement? Or a switch? Commented Mar 17, 2022 at 9:07
  • yes I know but I actually don't know what to put in it... I first thought of putting this.color.equals(...), but that doesn't seem to work Commented Mar 17, 2022 at 9:15

2 Answers 2

1

If this element is RED, you want to return YELLOW; otherwise you want to return RED. So

public enum Color {
    RED, YELLOW;
    public Color opposite() {
        if (this==Color.RED) {
            return Color.YELLOW;
        }
        return Color.RED;
    }
}

The opposite() method can be written more concisely as:

public Color opposite() {
    return (this==Color.RED ? Color.YELLOW : Color.RED);
}

or, if you want to allow for more enum values, as:

public Color opposite() {
    switch (this) {
        case RED: return Color.YELLOW;
        case YELLOW: return Color.RED;
        // other possible values
    }
    // required for compiler
    return null;
}

As Holger suggests, Java 12 onwards supports switch expressions, which offer a cleaner alternative:

public Color opposite() {
    return switch (this) {
        case RED -> Color.YELLOW;
        case YELLOW -> Color.RED;
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

Oh I see how the grammar works now. This'll help me with my other methods... Thanks you :)
In recent Java versions, you can write return switch(this) { case RED -> Color.YELLOW; case YELLOW -> Color.RED; }; without the need for a dummy default case.
@Holger Good suggestion.
0

Try using switch for this.

 public class Main {
    enum Color {
        RED,
        YELLOW;
    }
    public static void main(String[] args) {
    }
    public Color opposite() {
        Color myColor = Color.RED;
        return switch (myColor) {
            case RED -> Color.YELLOW;
            case YELLOW -> Color.RED;
        };
    }

}

If you prefer to use if statement instead of switch. You can try this instead

public Color opposite() {
        Color myColor = Color.RED;
        if (myColor == Color.RED) {
            return Color.YELLOW;
        } else  if (myColor == Color.YELLOW) {
            return Color.RED;
        }
        return null;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.