Console based command processing: Mapping string to enum in java
For my java console application, I need to call a set of functions with user given argum开发者_如何学Goents. My operations O1, O2, .. O5 are defined as an enum as
enum Operations {O1, O2, O3, O4, O5};
I need to read user input args[0] and call function F1, F2,...F5.
For example user is going to give:
>java MyApp O1 5 6
For this I suppose I need to map sting (args[0]) to an enum so that I can use switch select. How to do this?
Enum.valueOf(Class, String)
.
Example
Operations oper = Enum.valueOf(Operations.class, args[0]);
Will throw an exception if there are no enum values that matches args[0]
I suppose using what chuk lee 's lead you can come up with pritty cool program here what I did.
public class Main {
public static void main(String[] args) {
if(args.length < NUMBER_OF_OPERATORS){
throw new IllegalArgumentException(INSUFFICIENT_OPERANDS);
}
Operator operator = Enum.valueOf(Operator.class,
args[OPERATION_NAME].toUpperCase());
System.out.println(operator.operate(args[FIRST_OPERAND],
args[SECOND_OPERAND]));
}
private enum Operator {
ADD,SUBSTRACT,MULTIPLY,DIVIDE;
public String operate(String aString, String bString) {
int a = Integer.valueOf(aString);
int b = Integer.valueOf(bString);
int out = 0;
switch(this) {
case ADD : out = a + b; break;
case SUBSTRACT : out = a - b; break;
case MULTIPLY : out = a * b; break;
case DIVIDE : out = a / b; break;
default: throw new UnsupportedOperationException();
}
return String.valueOf(out);
}
}
private static final int NUMBER_OF_OPERATORS = 3;
private static final int OPERATION_NAME = 0;
private static final int FIRST_OPERAND = 1;
private static final int SECOND_OPERAND = 2;
private static final String INSUFFICIENT_OPERANDS =
"Insufficient operads to carry out the operation.";
}
精彩评论