我试图添加一个自定义函数,将数字求和到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);
    }
}


但它打印出10的“ 2”个instad

最佳答案

您可以尝试使用此构造函数告诉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());
}


希望这可以帮助,

坦率

10-06 03:41