I'm currently hardcoding an enum value, which is running through a switch statement. Is it possible to determine the enum based on user input.
Choice month = Choice.D;
Instead of hardcoding the value D
, can I use the user input here?
package partyAffil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class partyAffil {
public static void main(String[] args) {
System.out.println("Choose from the following menu");
System.out.println("D, R, or I");
String choice = getInput("please choose a letter.");
Choice month = Choice.D;
switch(month){
case D:
System.out.println("You get a Democratic Donkey");
break;
case R:
System.out.println("You get a Republican Elephant");
break;
case I:
System.out.println("You get an Independent Person");
break;
default:
System.out.println("You get a unicorn");
break;
}
}
public enum Choice{
D, R, I;
}
private static String getInput(String prompt)
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try{
return stdin.readLine();
} catch (Exception e){
return "Error: " + e.getMessage();
}
}
}
Each enum constant have its own name as declared in its declaration. Static method
valueOf
of particular enum returns the enum constant of this type by name.Thus, instead:
just use this: