如何更改Java中的枚举价值?

发布于 2025-01-28 01:20:27 字数 1399 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴我心暖 2025-02-04 01:20:27

您可以直接在枚举内部添加旋转/转盘方法。

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文