如何计算以字符串形式给出的数学表达式? [关闭]

本文翻译自:How to evaluate a math expression given in string form? [closed]

I'm trying to write a Java routine to evaluate simple math expressions from String values like: 我正在尝试编写Java例程,以从类似String值评估简单的数学表达式:

  1. "5+3"
  2. "10-40"
  3. "10*3"

I want to avoid a lot of if-then-else statements. 我想避免很多if-then-else语句。 How can I do this? 我怎样才能做到这一点?


#1楼

参考:https://stackoom.com/question/EMOP/如何计算以字符串形式给出的数学表达式-关闭


#2楼

This article discusses various approaches. 本文讨论了各种方法。 Here are the 2 key approaches mentioned in the article: 这是本文中提到的2种关键方法:

JEXL from Apache Apache的JEXL

Allows for scripts that include references to java objects. 允许包含对Java对象的引用的脚本。

// Create or retrieve a JexlEngine
JexlEngine jexl = new JexlEngine();
// Create an expression object
String jexlExp = "foo.innerFoo.bar()";
Expression e = jexl.createExpression( jexlExp );

// Create a context and add data
JexlContext jctx = new MapContext();
jctx.set("foo", new Foo() );

// Now evaluate the expression, getting the result
Object o = e.evaluate(jctx);

Use the javascript engine embedded in the JDK: 使用JDK中嵌入的javascript引擎:

private static void jsEvalWithVariable()
{
    List<String> namesList = new ArrayList<String>();
    namesList.add("Jill");
    namesList.add("Bob");
    namesList.add("Laureen");
    namesList.add("Ed");

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");

    jsEngine.put("namesListKey", namesList);
    System.out.println("Executing in script environment...");
    try
    {
      jsEngine.eval("var x;" +
                    "var names = namesListKey.toArray();" +
                    "for(x in names) {" +
                    "  println(names[x]);" +
                    "}" +
                    "namesListKey.add(\"Dana\");");
    }
    catch (ScriptException ex)
    {
        ex.printStackTrace();
    }
}

#3楼

You can also try the BeanShell interpreter: 您也可以尝试BeanShell解释器:

Interpreter interpreter = new Interpreter();
interpreter.eval("result = (7+21*6)/(32-27)");
System.out.println(interpreter.get("result"));

#4楼

How about something like this: 这样的事情怎么样:

String st = "10+3";
int result;
for(int i=0;i<st.length();i++)
{
  if(st.charAt(i)=='+')
  {
    result=Integer.parseInt(st.substring(0, i))+Integer.parseInt(st.substring(i+1, st.length()));
    System.out.print(result);
  }         
}

and do the similar thing for every other mathematical operator accordingly .. 并相应地对所有其他数学运算符执行类似的操作。


#5楼

HERE is another open source library on GitHub named EvalEx. 这里是GitHub上另一个名为EvalEx的开源库。

Unlike the JavaScript engine this library is focused in evaluating mathematical expressions only. 与JavaScript引擎不同,此库仅专注于评估数学表达式。 Moreover, the library is extensible and supports use of boolean operators as well as parentheses. 此外,该库是可扩展的,并支持布尔运算符和括号的使用。


#6楼

Another way is to use Spring Expression Language or SpEL which does a whole lot more along with evaluating mathematical expressions therefore maybe slightly overkill. 另一种方法是使用Spring Expression Language或SpEL,它在评估数学表达式方面做得更多,因此可能有点过大。 You do not have to be using Spring framework to use this expression library as it is stand-alone. 您不必使用Spring框架来使用此表达式库,因为它是独立的。 Copying examples from SpEL's documentation: 从SpEL文档中复制示例:

ExpressionParser parser = new SpelExpressionParser();
int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2 
double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); //24.0

Read more concise SpEL examples here and the complete docs here 阅读更简洁的规划环境地政司的例子在这里和完整的文档在这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值