java - 如何比较 enum 和 int?

标签 java enums

我正在尝试使用枚举来更改颜色,我正在将枚举与 int 进行比较,但它一直抛出错误

public class Game {

public enum State{
    RED, YELLOW, BLANK;
}

public State getState(int x, int y) {
    y=1;
    for (x=5;x>0;x--) {
  if (x== BLANK && y== BLANK) {
        return State.RED;
    }
    //return State.BLANK;
}
    return State.BLANK;
}

如何比较 int 和 enum?这样我就可以更改第一列 y 中设置为 1 的颜色

最佳答案

只需使用 Enum.ordinal()枚举的方法,用于获取从 0 到 X 的有序数,您可以将其与 x 变量进行比较:

public class Game {
    public enum State {
        BLANK,   // 0
        RED,     // 1
        YELLOW   // 2
    }

    public State getState(int x, int y) {
        y = 1;
        for (x = 5; x > 0; x--) {
            if (x == State.BLANK.ordinal() && y == State.BLANK.ordinal()) {
                return State.RED;
            }
            //return State.BLANK;
        }
        return State.BLANK;
    }
}

关于java - 如何比较 enum 和 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21578432/

相关文章:

java - 即使我们在不同的线程中使用不同的锁,为什么值设置正确

java - 注册 ItemBlock 的方法比我这里的更好吗?

javascript - 类枚举 setter ,约定 javascript

c# - 字典的 WCF 反序列化,其中枚举类型是关键

php - Laravel Php 8.1 如何将枚举案例转换为数组以选择输入

Java 无符号 - 删除符号位

java - 无法使用 Java 连接到 Azure 上的 Postgres 数据库

java - 允许斜杠的 JAX-RS @Path 与其他资源发生冲突

xml - 如何在 xml 中做一个枚举

c# - 为什么 C# 允许无效的枚举值