A fun alternative would be to use an enumeration. This will work if you want to define all the values ββin the class. This will simplify the code used to get the text value. And that gives you a few more extra features besides what the switch statement will give you.
enum NumberText { HELLO(1), WORLD(2); private static final HashMap<Integer,NumberText> map = new HashMap<Integer,NumberText>(); static{ for (ConnectionGenerator c : ConnectionGenerator.values()) { map.put(c.code, c); } } Integer code; NumberText(Integer pCode) { this.code = pCode; } Static ConnectionGenerator getTextFor(Integer code) { return map.get(code); } }
Then, to get the text, simply do the following:
NumberText nt = NumberText.getTextFor(USER_INPUT); System.out.println(nt);
You can get a fancier and put an extra constructor variable in the enumeration and have a specific line of text.
enum NumberText { HELLO(1, "Hello to You"), GOODBYE(2, "Goodbye"); private static final HashMap<Integer,NumberText> map = new HashMap<Integer,NumberText>(); static{ for (ConnectionGenerator c : ConnectionGenerator.values()) { map.put(c.code, c); } } Integer code; String text; NumberText(Integer pCode, String pText) { this.code = pCode; this.text = pText; } ConnectionGenerator getNumberTextFor(Integer code) { return map.get(code); } getText() { return this.text; } }
Then you can get the text as follows:
NumberText.getNumberTextFor(USER_INPUT).getText();
source share