views:

27

answers:

3
public void turnRight() {
        int direction=getDirection();
        if (direction==3)
            direction=0;
        else
            direction++;
        this.setDirection(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?

+2  A: 
direction++;
direction%=4;
Thilo
Ya ok 4 works..that was easy, thanks
fprime
A: 
int direction = getDirection();
direction++;  
direction = direction % 4;
Andrei
%3 must be wrong...
Thilo
I think, in this case, you should consider % 4.
Dean J
Max value of direction should be 3, not 2.
andersoj
yeah, you are right. I saw at another answer and thought I misunderstood something. sorry for that.
Andrei
A: 

public void turnRight(){this.setDirection(getDirection()%4==3?0:getDirection() + 1);}

Justin
I think, in this case, you should consider % 4.
Dean J
yep - had to think that through twice.
Justin