I am trying to change the color by using an enum, I am comparing an enum to an int but it keeps throwing an error
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;
}
How do I compare an int to an enum? so that I can change the color in the first column y which is set to 1
Cast Int To Enum may be of some help. Go with the 2nd option. The 1st one can cause an exception if the integer is out of the defined range in your Enumeration. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.
We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
Just use the Enum.ordinal() method of an enum to get the ordered number from 0 to X which you can compare to your x
variable:
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;
}
}
You have to assign values to the enum. As is, it's trying to compare two things which aren't comparable.
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;
}
}
you could use ordinal()
. It returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
In your case RED.ordinal()
would return 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With