1
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
  • 1
    yes, you'd need to manually wrap around Commented Nov 17, 2021 at 11:14
  • 1
    honestly I would not bother valueOf(). Just check their ordinal() with % Commented Nov 17, 2021 at 12:05

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1
if (b == Direction.values()[(a.ordinal() + 1) % Direction.values().length])
Suraj Rao
29.7k11 gold badges96 silver badges104 bronze badges
answered Nov 17, 2021 at 11:36

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.