如何更改 Java 中的枚举值?
How to change an enum value in Java?
我有一个枚举 Direction
,它显示了合法的步行方向。使用辅助方法 turnLeft
我想改变被调用的枚举变量的值,但是它不起作用:方法调用后枚举变量的值direction
相同
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;
}
}
我做错了什么?
您可以直接在枚举中添加 turnLeft/turnRight 方法。
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
}
}
}
然后每当你想转弯时,你可以将“左”值赋给方向变量。
private Direction direction = Direction.DOWN;
public void turnAndPrint() {
direction = direction.turnLeft();
System.out.println(direction.name()); // will print RIGHT when called the first time
}
我有一个枚举 Direction
,它显示了合法的步行方向。使用辅助方法 turnLeft
我想改变被调用的枚举变量的值,但是它不起作用:方法调用后枚举变量的值direction
相同
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;
}
}
我做错了什么?
您可以直接在枚举中添加 turnLeft/turnRight 方法。
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
}
}
}
然后每当你想转弯时,你可以将“左”值赋给方向变量。
private Direction direction = Direction.DOWN;
public void turnAndPrint() {
direction = direction.turnLeft();
System.out.println(direction.name()); // will print RIGHT when called the first time
}