我有2个整数:
int first= 10;
int second = 20;
和表示操作的字符串(+
,-
,/
或*
之一):
String op = "+";
如何在此示例中获得10 + 20的结果?
答案 0 :(得分:13)
我不推荐这个,但很有趣。在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);
使用开关,但记得将字符串运算符转换为char,因为开关不适用于字符串。
switch(op.charAt(0)){
case '+':
return first + second;
break;
// and so on..
答案 1 :(得分:6)
switch (op.charAt(0)) {
case '+':
return first + second;
break;
case '-':
return first - second;
break;
// ...
}
答案 2 :(得分:3)
您可以尝试以下代码。它是面向对象的,非常通用的,您可以轻松地扩展它以添加新的运算符,包括具有不同数量的参数的运算符:
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);
}
答案 3 :(得分:1)
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;
}
}
答案 4 :(得分:0)