Java - How to go the first item when you add one to the max in a list?

Yonetmen :

I have 4 directions with ids of 1, 2, 3, 4. (North,East,South,West)

If I want to turn left i get the current Id and minus 1. I think I figured out the algoritm for this.

int currentDirection = 1;
currentDirection = (currentDirection - 1) % 4 + 4;

If current direction is 1 (North) and I want to go left (minus), I get this result:

Result: 4

So it's working. Works with all directions. But I can't figure out how to get correct result when I want to go to the righ (plus). I have tried this code. It works if the current direction is 1, 2 or 4. But it's not working when current direction is 3 (South)

int currentDirection = 3;
currentDirection = (currentDirection + 1) % 4;

Will result like this.

Result: 0
J.Z :

Right Turn: currentDirection = currentDirection % 4 + 1

Left Turn: currentDirection = (currentDirection+2) % 4 + 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164047&siteId=1