Calculator without if/else or switch

天大地大妈咪最大 提交于 2020-02-25 06:05:16

问题


I am trying to write calculator for + - * / without conditions. The operator is stored as a string.

Is there anyway to achieve it?

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ////String Operator = "";
        String L1="";
        String L2="";
        String op = "+";
        double a = 3;
        double b = 2;

        //Operator p = p.
        Operator p;
        b = Operator.count(a, op, b);
        System.out.println(b);
    }

    public enum Operator {
        PLUS("+"), MINUS("-"), DIVIDE("/"), MULTIPLY("*");

        private final String operator;

        public static double count(double a,String op,double b) {
            double RetVal =0;
            switch (Operator.valueOf(op)) {
            case PLUS:
                RetVal= a + b;
            case MINUS:
                RetVal= a - b;
            case DIVIDE:
                RetVal= a / b;
            case MULTIPLY:
                RetVal= a * b;
            }
            return RetVal;
        }

        Operator(String operator) {
            this.operator = operator;

        }
        // uniwersalna stała grawitacyjna (m3 kg-1 s-2)
    }

}

Got this error:

Exception in thread "main" java.lang.IllegalArgumentException: No enum const class Main$Operator.+

Any clues?


回答1:


You could use a strategy pattern and store a calculation strategy for each operator.

interface Calculation {
  double calculate(double op1, double op2);
}

class AddCalculation implements Calculation {
  double calculate(double op1, double op2) {
    return op1 + op2;
  }
}

//others as well

Map<String, Calculation> m = ...;

m.put("+", new AddCalculation());

During execution you then get the calculation objects from the map and execute calculate().




回答2:


i think using an enum would be a nice option:

Enum Operation{
PLUS("+")
MINUS("-")
DIVIDE("/")
MULTIPLY("*")
}

then you could go with

switch(Operation.valueOf(userInputString)){
case PLUS: return a+b;
case MINUS: return a-b;
case DIVIDE: return a/b;
case MULTIPLY: return a*b;
}



回答3:


how about hashing? Hash the operators as a key-value pair ("+": +). For the string operatory, hash it and grab the value. Experiment with that




回答4:


As mentioned by Peter Lawrey, ScriptEngine/JavaScript might be a good choice for this. Visit this little JavaScript interpreter applet to explore the possibilities.



来源:https://stackoverflow.com/questions/5926155/calculator-without-if-else-or-switch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!