我试图+ - * /无条件地写计算器.运算符存储为字符串.
反正有没有实现它?
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)
}
}
Run Code Online (Sandbox Code Playgroud)
得到此错误:
线程"main"中的异常java.lang.IllegalArgumentException:No enum const class Main $ Operator.+
有线索吗?
Tho*_*mas 11
您可以使用策略模式并为每个运算符存储计算策略.
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());
Run Code Online (Sandbox Code Playgroud)
在执行期间,您可以从地图中获取计算对象并执行calculate().
| 归档时间: |
|
| 查看次数: |
4535 次 |
| 最近记录: |