[英]Performing math operation when operator is stored in a string
I have 2 integers:我有 2 个整数:
int first= 10;
int second = 20;
and a string representing the operation (one of +
, -
, /
, or *
):和表示操作的字符串(
+
、 -
、 /
或*
):
String op = "+";
How can I get the result of 10 + 20 in this example?在这个例子中我怎样才能得到 10 + 20 的结果?
I don't recommend this but is funny.我不推荐这个,但很有趣。 in java6
在java6中
String op = '+';
int first= 10;
int second = 20;
ScriptEngineManager scm = new ScriptEngineManager();
ScriptEngine jsEngine = scm.getEngineByName("JavaScript");
Integer result = (Integer) jsEngine.eval(first+op+second);
go with the switch, but remember to convert the string operator to char as switch don't works with strings yet.使用 switch,但请记住将字符串运算符转换为 char,因为 switch 还不适用于字符串。
switch(op.charAt(0)){
case '+':
return first + second;
break;
// and so on..
switch (op.charAt(0)) {
case '+': return first + second;
case '-': return first - second;
// ...
}
you can try the following code.你可以试试下面的代码。 It's object oriented, quite generic, and you can easily extend it to add new operators, including operators with a different number of arguments:
它是面向对象的,非常通用,您可以轻松扩展它以添加新的运算符,包括具有不同数量参数的运算符:
public abstract class Operator {
public abstract Integer compute(Integer...values);
}
public class Plus extends Operator {
public Integer compute(Integer...values) {
return values[0] + values[1];
}
}
public class Minus extends Operator {
public Integer compute(Integer...values) {
return values[0] - values[1];
}
}
public class Multiply extends Operator {
public Integer compute(Integer...values) {
return values[0] * values[1];
}
}
public class Divide extends Operator {
public Integer compute(Integer...values) {
return values[0] / values[1];
}
}
Map operatorMap = createOperatorMap();
public Map createOperatorMap() {
Map<String, Operator> map = new HashMap<String, Operator>();
map.put("+", new Plus());
map.put("-", new Minus());
map.put("*", new Multiply());
map.put("/", new Divide());
return map;
}
public int compute(int a, int b, String opString) {
Operator op = operatorMap.get(opString);
if (op == null)
throw new IllegalArgumentException("Unknown operator");
return op.compute(a, b);
}
public double doMath(int first, int second, char op ){
switch(op){
case '+':
return first + second;
break;
case '-':
return first - second;
break;
case '*':
return first * second;
break;
case '/':
return first / second;
break;
default:
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.