0

I have an enum Direction which shows legal walking directions. With the helper-method turnLeft I want to change the value of the called enum Variable, but it does not work: The value of the enum Variable directionis the same after the call of the method.

enum Direction{    
    UP, RIGHT, DOWN, LEFT
}

private Direction direction = Direction.DOWN;

public void turnLeft(Direction direction) {

    switch(direction) {
        case UP: this.direction = Direction.LEFT; break;
        case RIGHT: this.direction = Direction.UP; break;
        case DOWN: this.direction = Direction.RIGHT; break;
        case LEFT: this.direction = Direction.DOWN; break;
    }

}

What am I doing wrong?

  • 2
    Please explain ["does not work"](https://web.archive.org/web/20180124130721/http://importblogkit.com/2015/07/does-not-work/). Use [edit] option to clarify your question. Your method changes `this.direction` *field* based on value provided as `direction` argument (regardless of what `this.direction` field was holding). – Pshemo May 11 '22 at 19:54
  • Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – knittl May 11 '22 at 19:55
  • 2
    I would suggest to have a look over [state machines](https://www.baeldung.com/java-enum-simple-state-machine#enums-states) – alexandrum May 11 '22 at 20:08
  • 1
    I suspect the `turnLeft` method should not take any arguments. The `switch` statement should be based on the private field, not a method argument. – VGR May 11 '22 at 20:59

1 Answers1

3

You can add the turnLeft/ turnRight methods directly inside the enum.

enum Direction{
    UP, RIGHT, DOWN, LEFT;

    public Direction turnLeft() {
        switch(this) {
            case UP: return LEFT;
            case RIGHT: return UP;
            case DOWN: return RIGHT;
            default: return DOWN; // if you leave the LEFT case, you still need to return something outside the block on some Java versions
        }
    }
}

and then whenever you want to make a turn, you can assign the "left" value to the direction variable.

private Direction direction = Direction.DOWN;

public void turnAndPrint() {
    direction = direction.turnLeft();
    System.out.println(direction.name()); // will print RIGHT when called the first time
}
thinkgruen
  • 929
  • 10
  • 15