如何在java中评估字符串数学表达式

时间:2015-03-25 09:40:03

标签: java string math scriptengine symja

我想在java中评估一个sting数学表达式。该字符串应包含应用于向量或简单数字的函数(avg,max,min,...)。 我已经将ScriptEngineManager与javasript引擎一起使用,但它只使用数字。我也看到了symja lib,但它看起来太复杂了,没有记录。怎么做? 感谢

2 个答案:

答案 0 :(得分:0)

看一下javadoc的Math和String类。如果您知道字符串的格式,您应该能够搜索它以查找您正在使用的特定数字和功能。如果你只使用每个输入的avg / max / min之一,那应该很容易。

以下是一个示例,假设您希望它的格式如此(如果每个值后面都有逗号,则很容易):

"功能(a,b,c,)" - > " MIN(3,6,8,)"

你要做的第一件事是弄清楚你正在做什么功能。使用indexOf方法,我们可以确定它是否包含MIN或MAX等等。

 if(expression.indexOf("MIN" != -1){
      //calculate min value
 }

您还需要创建一个包含您正在使用的所有号码的列表。

 int lastIndex = exression.indexOf("(");
 while(lastIndex < expression.lastIndexOf(","){
      listOfNums.add(Integer.parseInt(expression.subString(lastIndex + 1, expression.indexOf(",", lastIndex + 1)));
      lastIndex = expression.indexOf(",", lastIndex + 1);
  }

答案 1 :(得分:0)

有两个非常好的表达式解析器,JEP(现在很遗憾地付费 - http://www.singularsys.com/jep/)和Jexl(不仅仅是表达式解析器 - http://commons.apache.org/proper/commons-jexl/)。

我更喜欢Jexl,所以这是一个例子:

JexlEngine jexl = new JexlEngine();
// The expression to evaluate
Expression e = jexl.createExpression("((a || b) || !c) && !(d && e)");

// Populate the context
JexlContext context = new MapContext();
context.set("a", true);
context.set("b", true);
context.set("c", true);
context.set("d", true);
context.set("e", true);

// Work it out
Object result = e.evaluate(context);

更多示例 - http://commons.apache.org/proper/commons-jexl/reference/examples.html

干杯...

相关问题