算术运算符为枚举?

时间:2016-03-19 16:00:12

标签: java enums operators

我的程序提示用户选择其中一个算术运算符(+, - ,*,/)并将其响应存储在变量inOperator中。在以下case语句中(位于main方法中),我想相应地设置positiveOperatonnegativeOperation

switch (inOperator){
        case 1: operator = '+';
            //positiveOperation = plus
            //negativeOperation = minus
        break;

        case 2: operator = '-';
            //positiveOperation = minus
            //negativeOperation = plus
        break;

       ...
    }

我已经创建了一个初始化算术运算的枚举:

public enum Operator
{        
    plus("+") {
        @Override public double apply(double v1, double v2) {
        return v1 + v2;
        }
    },
    minus("-") {
        @Override public double apply(double v1, double v2) {
            return v1 - v2;
        }
    },

    ...

    private final String text;
    private Operator(String text) {
        this.text = text;
    }
    public abstract double apply(double x1, double x2);
    @Override public String toString() {
        return text;  
    }
}

回到案例陈述,如何设置positiveOperationnegativeOperation?我可以创建另一个初始化这两个的枚举吗?

4 个答案:

答案 0 :(得分:1)

我不确定我是否理解这个问题,也不知道你为什么要这样做。以下是什么意思?

switch (inOperator) {
case 1:
    operator = '+';
    positiveOperation = Operator.plus;
    negativeOperation = Operator.minus;
    break;

case 2:
    operator = '-';
    positiveOperation = Operator.minus;
    negativeOperation = Operator.plus;
    break;

// ...

}

答案 1 :(得分:1)

要将用户输入转换为您的某个操作符,您可以编写如下函数:

public Operator operatorFromInput(char input) {
    switch (input) {
    case '+':
        return Operator.plus;
    case '-':
        return Operator.minus;
    }
    return null;
}

答案 2 :(得分:1)

将此添加到您的枚举:

public static Operator fromChar(String operator) {
    for (Operator op : Operator.values()) {
        if (op.text.equals(operator)) return op;
    }
    throw new IllegalArgumentException("Received a fishy operator: " + operator);
}

然后,一旦你读入inOperator,你就可以做到:

Operator operator = Operator.fromChar(inOperator);
int y = operator.apply(x1, x2);

答案 3 :(得分:1)

这可能对您有用:

public enum Operator implements BinaryOperator<Double> {
    plus("+") {
        public Double apply(Double v1, Double v2) {
            return v1 + v2;
        }
    },
    minus("-") {
        public Double apply(Double v1, Double v2) {
            return v1 - v2;
        }
    };

    private final String text;

    Operator(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public static Operator from(String str) {
        return Arrays.stream(values()).filter(o -> o.text.equals(str)).findFirst()
            .orElseThrow(IllegalArgumentException::new);
    }
}