我的程序提示用户选择算术运算符之一(+、-、*、/)并将其响应存储在变量 inOperator
中。在下面的 case 语句中(位于 main 方法中),我想相应地设置一个 positiveOperaton
和 maleOperation
。
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;
}
}
那么回到 case 语句,如何设置 positiveOperation
和 maleOperation
?我可以创建另一个枚举来初始化这两个吗?
最佳答案
这可能对你有用:
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);
}
}
关于java - 算术运算符作为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36103878/