我试图通过使用枚举来改变颜色,我将枚举与int进行比较,但它不断抛出错误
如何将int与枚举进行比较?这样我就可以改变第一列y中设置为1的颜色
答案 0 :(得分:5)
只需使用枚举的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;
}
}
答案 1 :(得分:4)
您必须为枚举值指定值。它就是在尝试比较两个不具有可比性的东西。
public class Game {
public enum State{
RED(1), YELLOW(2), BLANK(0);
private int val;
private State(int value){
val = value;
}
public int getValue(){
return val;
}
}
public State getState(int x, int y) {
y=1;
for (x=5;x>0;x--) {
if (x== State.BLANK.getValue() && y== State.BLANK.getValue()) {
return State.RED;
}
//return State.BLANK;
}
return State.BLANK;
}
}
答案 2 :(得分:1)
您可以使用ordinal()
。它返回此枚举常量的序数(它在枚举声明中的位置,其中初始常量的序数为零)。
在您的情况下,RED.ordinal()
将返回0。