1

我正在尝试添加一个自定义函数,将数字求和到 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

4

1 回答 1

0

你能试试这个构造函数告诉 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());
}

希望这可以帮助,

坦率

于 2013-02-06T15:57:32.237 回答