基于控制台的命令处理:将字符串映射到java中的枚举

时间:2010-10-28 01:36:24

标签: java

对于我的java控制台应用程序,我需要使用用户给定的参数调用一组函数。我的操作O1,O2,... O5被定义为枚举为

enum Operations {O1, O2, O3, O4, O5};

我需要读取用户输入args [0]并调用函数F1,F2,... F5。

例如,用户将给出:

>java MyApp O1 5 6

为此,我想我需要将sting(args [0])映射到枚举,以便我可以使用switch select。怎么做?

2 个答案:

答案 0 :(得分:2)

Enum.valueOf(Class, String)

实施例

Operations oper = Enum.valueOf(Operations.class, args[0]);

如果没有与args[0]匹配的枚举值

,则会抛出异常

答案 1 :(得分:0)

我认为使用chuk lee的主导你可以拿出pritty酷程序 这就是我做的。

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

}