public enum Direction {
UP,
RIGHT,
DOWN,
LEFT,
}
i have two enum variables (a and b), in one case i have to check, if b
is the next of a
for example
if a=UP
and b=RIGHT
.
and also if a=left
and b=UP
.
mabe something like this:
if(Direction.valueOf(a+1)==Direction.valueOf(b))
but when a=LEFT
it would be out of bounds like an array right ?
asked Nov 17, 2021 at 11:13
2 Answers 2
Try this.
public enum Direction {
UP,
RIGHT,
DOWN,
LEFT;
private static final Direction[] VALUES = values();
public Direction next() {
return VALUES[(ordinal() + 1) % VALUES.length];
}
}
public static void main(String[] args) {
Direction a = Direction.LEFT;
Direction b = Direction.UP;
System.out.println(a.next() == b);
}
output:
true
answered Nov 17, 2021 at 11:42
user17233545user17233545
Sign up to request clarification or add additional context in comments.
Comments
if (b == Direction.values()[(a.ordinal() + 1) % Direction.values().length])
Suraj Rao
29.7k11 gold badges96 silver badges104 bronze badges
1 Comment
Neeraj
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
lang-java
valueOf()
. Just check theirordinal()
with%