Java Modulo Help
public void turnRight() {
int direction=getDirection();
if (direction==3)
direction=0;
else
direction++;
this.setDirect开发者_JAVA百科ion(direction);
So I have this method that, when called, increments direction by 1. However, the max value should be 3, so if direction is equal to 3 and the method is called, then it should go back to zero. What I have works, but I'm sure there is a way to do this using the % operator. Can anyone show me how?
direction++;
direction%=4;
int direction = getDirection();
direction++;
direction = direction % 4;
public void turnRight(){this.setDirection(getDirection()%4==3?0:getDirection() + 1);}
精彩评论