What's the proper way to compare a String to an enum value?
I'm gathering from your question that userPick
is a String
value. You can compare it like this:
if (userPick.equalsIgnoreCase(computerPick.name())) . . .
As an aside, if you are guaranteed that computer
is always one of the values 1
, 2
, or 3
(and nothing else), you can convert it to a Gesture
enum with:
Gesture computerPick = Gesture.values()[computer - 1];
You should declare toString()
and valueOf()
method in enum
.
import java.io.Serializable;
public enum Gesture implements Serializable {
ROCK,PAPER,SCISSORS;
public String toString(){
switch(this){
case ROCK :
return "Rock";
case PAPER :
return "Paper";
case SCISSORS :
return "Scissors";
}
return null;
}
public static Gesture valueOf(Class<Gesture> enumType, String value){
if(value.equalsIgnoreCase(ROCK.toString()))
return Gesture.ROCK;
else if(value.equalsIgnoreCase(PAPER.toString()))
return Gesture.PAPER;
else if(value.equalsIgnoreCase(SCISSORS.toString()))
return Gesture.SCISSORS;
else
return null;
}
}
My idea:
public enum SomeKindOfEnum{
ENUM_NAME("initialValue");
private String value;
SomeKindOfEnum(String value){
this.value = value;
}
public boolean equalValue(String passedValue){
return this.value.equals(passedValue);
}
}
And if u want to check Value u write:
SomeKindOfEnum.ENUM_NAME.equalValue("initialValue")
Kinda looks nice for me :). Maybe somebody will find it useful.