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 ??? }
-
Do you know how to write an if statement? Or a switch?khelwood– khelwood2022-03-17 09:07:12 +00:00Commented 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 workHeyy– Heyy2022-03-17 09:15:57 +00:00Commented Mar 17, 2022 at 9:15
Add a comment
|
2 Answers
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;
};
}
3 Comments
Heyy
Oh I see how the grammar works now. This'll help me with my other methods... Thanks you :)
Holger
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.khelwood
@Holger Good suggestion.
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;
}