Search code examples
javaenumsswitch-statementdefault

Using enums instead of switch in Java


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...


Solution

  • You can always catch the thrown exception and provide your own default

    InputChar c=InputChar.X;
    trý {
     c=InputChar.valueOf(charEntered);
    } catch (IllegalArgumentException e){
     System.out.println("I don't know what to do with " + charEntered+", defaulting to X");
    
    }