I am using enum instead of switch, but there is an issue. In a switch you can have a default case. But what about using enums? My program crashes when I give an input different than the defined enums.
For example:
public enum InputChar {
X,Y,Z;
/**
* get an input character
* @return a String description of the input character
*/
@Override
public String toString()
{
String s = "";
if (this.ordinal() == 0)
s = "X";
else if (this.ordinal() == 1)
s = "Y";
else if (this.ordinal() == 2)
s = "Z";
return s;
}
}
I'm using it in:
private void checkInput(String charEntered)
{
textDoc = new textDoc (InputChar.valueOf(charEntered));
}
I have researched and can't get it working. Thought about putting an else statement in toString(), but can't seem to put deafult in there...
Enum.ordinal(). Quoting the Javadoc: "Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.". See also Effective Java for a detailed description of why not to use it, e.g. fragility. Plus, the default implementation ofEnum.toString()produces the same output already.