用Java处理算术运算符

时间:2015-08-22 08:44:54

标签: java

我有四个类来处理数学运算:PlusMultiplyDivideMinus

我的输入是这样的:

1, 2, +

现在我的问题是:我们如何确定运算符的类型然后调用正确的类?(没有if-else或switch-case的实现)

2 个答案:

答案 0 :(得分:1)

您可以使用Map<Character,Object>来存储字符和对象,以便在单个结构中进行计算,稍后只使用字符访问if-elseswitch

Map<Character,Object> map = new HashMap<>();
map.put('+', plusObject);
map.put('-', minusObject);
map.put('*', multiplyObject);
map.put('/', divideObject);
  

现在我的问题是:我们如何确定运营商的类型   然后打电话给正确的班级?

map.get(character)它将根据字符返回对象,否则返回null

答案 1 :(得分:0)

为操作对象创建一个接口。让他们实施它。

public interface OperationObject {
    public int eval(int a, int b);
}

然后像这样或类似的

使用它
public class Handler {
    private HashMap<Character, OperationObject> operationMap = new HashMap<Character, OperationObject>();

    public Handler() {
        operationMap.put('+', new additionObject());
        operationMap.put('-', new subtractionObject());
        operationMap.put('*', new multiplicationObject());
        operationMap.put('/', new divisionObject());
    }

    public int doOperation(int number1, int number2, char operation) {
        return operationMap.get(operation).eval(number1, number2);
    }
}

这是我能做的最好的,无需为你编写操作类。

doSomething应该是你的类中执行操作的方法,实际上你应该使用上面定义的接口。