当操作符存储在字符串中时执行数学运算 [英] Performing math operation when operator is stored in a string
本文介绍了当操作符存储在字符串中时执行数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个整数:
int first= 10;
int second = 20;
以及表示操作的字符串( + $ c $之一c>,
-
, /
或 *
):
and a string representing the operation (one of +
, -
, /
, or *
):
String op = "+";
如何在此示例中获得10 + 20的结果?
How can I get the result of 10 + 20 in this example?
推荐答案
我不推荐这个,但很有趣。 in java6
I don't recommend this but is funny. in 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,因为开关不适用于字符串呢。
go with the switch, but remember to convert the string operator to char as switch don't works with strings yet.
switch(op.charAt(0)){
case '+':
return first + second;
break;
// and so on..
这篇关于当操作符存储在字符串中时执行数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文