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
}
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
}
发布评论
评论(1)
您可以直接在枚举内部添加旋转/转盘方法。
然后,只要您想转弯,就可以将“左”值分配给方向变量。
You can add the turnLeft/ turnRight methods directly inside the enum.
and then whenever you want to make a turn, you can assign the "left" value to the direction variable.