[英]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 arguments. 对于我的Java控制台应用程序,我需要使用用户给定的参数调用一组函数。 My operations O1, O2, .. O5 are defined as an enum as
我的操作O1,O2,... O5被定义为枚举
enum Operations {O1, O2, O3, O4, O5};
I need to read user input args[0] and call function F1, F2,...F5. 我需要读取用户输入args [0]并调用函数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. 为此,我想我需要将sting(args [0])映射到枚举,以便我可以使用switch select。 How to do this?
这个怎么做?
Enum.valueOf(Class, String)
. 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]
如果没有与
args[0]
匹配的枚举值,将抛出异常
I suppose using what chuk lee 's lead you can come up with pritty cool program here what I did. 我想使用chuk lee的线索,您可以在这里提出我的出色程序。
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.";
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.