'How to change an enum value in Java? [closed]

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?



Solution 1:[1]

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
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1