Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的Handle算术运算符_Java - Fatal编程技术网

Java中的Handle算术运算符

Java中的Handle算术运算符,java,Java,我有四门处理数学运算的课:加号,乘法,除法,减号 我的输入如下: 1, 2, + 现在我的问题是:如何确定运算符的类型,然后调用正确的类?(在没有if-else或switch-case的情况下实现)您可以使用映射,在这里您可以在单个结构中存储要计算的字符和对象,并在以后仅使用字符进行访问,而不使用任何if-else或开关 Map<Character,Object> map = new HashMap<>(); map.put('+', plusObject); map.

我有四门处理数学运算的课:
加号
乘法
除法
减号

我的输入如下:

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

您可以使用
映射
,在这里您可以在单个结构中存储要计算的字符和对象,并在以后仅使用字符进行访问,而不使用任何
if-else
开关

Map<Character,Object> map = new HashMap<>();
map.put('+', plusObject);
map.put('-', minusObject);
map.put('*', multiplyObject);
map.put('/', divideObject);
Map Map=newhashmap();
map.put('+',plusObject);
map.put('-',minusObject);
map.put('*',multiplyObject);
map.put('/',divideObject);
现在我的问题是:我们如何确定运算符的类型 那就给正确的班级打电话


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

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

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);
    }
}
公共类处理程序{
私有HashMap operationMap=新HashMap();
公共处理程序(){
operationMap.put('+',new additionObject());
operationMap.put('-',新减法对象());
operationMap.put('*',新的乘法对象());
operationMap.put('/',new divisionObject());
}
公共整数操作(整数1、整数2、字符操作){
返回操作map.get(操作).eval(编号1,编号2);
}
}
这是我能做的最好的了,不用为您编写操作类


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

如果您试图构建反向波兰符号解析器,那么我认为您为运算符创建类是走错了路。对不起,如何访问字符?