0

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

4

2 回答 2

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);
  }
于 2015-03-25T09:58:35.843 回答
0

有两个非常好的表达式解析器,JEP(不幸的是现在付费 - http://www.singularsys.com/jep/)和 Jexl(不仅仅是一个表达式解析器 - http://commons.apache.org/proper/公共-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

干杯...

于 2015-03-25T12:06:12.057 回答