作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试添加一个自定义函数,将数字求和到 ExpressionBuilder这是java代码:
package com.sapiens.bdms.drools.exe.helper.FuncServiceTrial;
import com.sapiens.bdms.drools.exe.helper.Functions;
import de.congrace.exp4j.*;
import java.util.ArrayList;
import java.util.Collection;
public class FormulaInterpreter {
public double interpret(String formula) throws UnparsableExpressionException, UnknownFunctionException, InvalidCustomFunctionException {
Collection<CustomFunction> customFunctions = new ArrayList<CustomFunction>();
customFunctions.add(new CustomFunction("SUM") {
@Override
public double applyFunction(double[] doubles) {
Double res = 0.0;
for (double aDouble : doubles) {
res += aDouble;
}
return res;
}
});
Calculable calc = (Calculable) new ExpressionBuilder(formula).withCustomFunctions(customFunctions).build();
return calc.calculate();
}
public static void main(String[] args) throws UnknownFunctionException, UnparsableExpressionException, InvalidCustomFunctionException {
FormulaInterpreter formulaInterpreter = new FormulaInterpreter();
double res = formulaInterpreter.interpret("SUM(2,4,4)");
System.out.println(res);
}
}
但它打印出“2”而不是 10
最佳答案
你能尝试这个构造函数告诉 exp4j 你的函数应该有多少个参数吗:
new CustomFunction("SUM",3)
如 API 文档中所述:http://www.objecthunter.net/exp4j/apidocs/de/congrace/exp4j/CustomFunction.html
这是一个有效的 JUnit 测试用例:
@Test
public void testCustomFunction21() throws Exception {
CustomFunction sumFunc = new CustomFunction("SUM",3) {
@Override
public double applyFunction(double[] doubles) {
Double res = 0.0;
for (double aDouble : doubles) {
res += aDouble;
}
return res;
}
};
Calculable calc = (Calculable) new ExpressionBuilder("SUM(2,4,4)").withCustomFunction(sumFunc).build();
assertTrue(10d == calc.calculate());
}
希望这有帮助,
弗兰克
关于java - de.congrace.exp4j 在 CustomFunction 的多个参数上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14710187/
我遇到了错误: Gradle: error: package de.congrace.exp4j does not exist 我将exp4j.jar文件添加到项目下: TestProject-ide
我正在尝试添加一个自定义函数,将数字求和到 ExpressionBuilder这是java代码: package com.sapiens.bdms.drools.exe.helper.FuncServ
我是一名优秀的程序员,十分优秀!