本文介绍了没有if / else或switch的计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试无条件为 +-* / 编写计算器。运算符存储为字符串。

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

反正有实现吗?

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)
    }

}

收到此错误:

任何线索?

推荐答案

您可以使用策略模式并为每个运算符存储计算策略。

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());

在执行期间,您可以从地图中获取计算对象并执行 calculate( )

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

这篇关于没有if / else或switch的计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:22