没有 if/else 或 switch 的计算器
我正在尝试无条件地为 + - * /
编写计算器。运算符存储为字符串。
有办法实现吗?
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)
}
}
得到这个错误:
线程“main”中出现异常 java.lang.IllegalArgumentException:没有枚举 const class Main$Operator.+
有任何线索吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用策略模式并为每个运算符存储计算策略。
在执行过程中,您可以从映射中获取计算对象并执行
calculate()
。You could use a strategy pattern and store a calculation strategy for each operator.
During execution you then get the calculation objects from the map and execute
calculate()
.我认为使用枚举将是一个不错的选择:
那么你可以选择
i think using an enum would be a nice option:
then you could go with
哈希怎么样?将运算符散列为键值对(“+”:+)。对于字符串运算符,对其进行散列并获取值。尝试一下
how about hashing? Hash the operators as a key-value pair ("+": +). For the string operatory, hash it and grab the value. Experiment with that
正如 Peter Lawrey 提到的,ScriptEngine/JavaScript 可能是一个不错的选择。访问这个JavaScript 解释器小程序来探索可能性。
As mentioned by Peter Lawrey, ScriptEngine/JavaScript might be a good choice for this. Visit this little JavaScript interpreter applet to explore the possibilities.