0

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

3
  • What are you actually trying to do? Commented Feb 18, 2016 at 14:56
  • Don't use 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 of Enum.toString() produces the same output already. Commented Feb 18, 2016 at 14:58
  • I want to limit my character input for the program to a few special characters. Here X,Y, and Z. Commented Feb 18, 2016 at 15:56

4 Answers 4

2

Two things:

  1. by default, an enum has a default implementation which just returns its .name(); therefore your override here is redundant;
  2. enums are classes "like any others" (nearly so) so they have constructors; if you want to "add" data to an enum, the correct way is as follows:

public enum MyEnum
{
    FOO("my data"),
    ;

    private final String whatever;

    MyEnum(final String whatever)
    {
        this.whatever = whatever;
    }

    public String getWhatever()
    {
        return whatever;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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");

}

Comments

0

There are three ways to do this:

if-else

Compare each ordinal value and return a corresponding value.

public enum InputChar {
    X, Y, Z;

    @Override
    public String toString() {
        if (this.ordinal() == 0) {
            return "X";
        } else if (this.ordinal() == 1) {
            return "Y";
        } else if (this.ordinal() == 2) {
            return "Z";
        } else {
            return "";
        }
    }
}

switch

Switch on the ordinal value and return a corresponding value.

public enum InputChar {
    X, Y, Z;

    @Override
    public String toString() {
        switch (this.ordinal()) {
            case 0:
                return "X";
            case 1:
                return "Y";
            case 2:
                return "Z";
            default:
                return "";
        }
    }
}

enum property

Return the assigned value of the enum.

public enum InputChar {
    X("X"),
    Y("Y"),
    Z("Z");

    private String value;

    private InputChar(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }
}

Optimized Lookup

The best way to quickly look up an enum by a property is to create a lookup table.

import java.util.LinkedHashMap;
import java.util.Map;

public enum InputChar {
    X("X"),
    Y("Y"),
    Z("Z");

    private static final Map<String, InputChar> lookup;
    static {
        lookup = new LinkedHashMap<>();
        for (InputChar inChar : values()) {
            lookup.put(inChar.value, inChar);
        }
    }

    private String value;

    private InputChar(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    public InputChar findByValue(String value) {
        return lookup.get(value);
    }
}

Comments

0

try below

 enum InputChar {
    X("X"),
    Y("Y"),
    Z("Z"),
    DEFAULT("D");

    private String value;

    private InputChar(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static InputChar getEnum(String value) 
    {
        for (InputChar v : values())
            if (v.toString().equalsIgnoreCase(value))
                return v;
        return InputChar.DEFAULT;
    }}

In main

System.out.println(InputChar.getEnum("X"));
System.out.println(InputChar.getEnum("A"));

It worked for me

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.