Calculable. Expressions with conditionals


I am trying to calculate a formula with java but when I try to use a conditional, to do one thing or another according to whether a parameter is true or false. I add method.

public void calcular (){
    Calculable calc = null;
    try {
        calc = new ExpressionBuilder("(4-2)/100").build();
    } catch (UnknownFunctionException e) {
    } catch (UnparsableExpressionException e) {
    double result1=calc.calculate();

This works perfect but when I try to put something like that in the expression it does not work:

(30>20 ? 3+2 : (4-2)/100); //esto por ejemplo.

Any ideas?

asked by mabts 18.07.2018 в 11:35

1 answer


I assume the use of the link library in version 0.4.X:

The problem is that the default operators of that library do not find the ternary operator nor the operator greater than

The solution would be to add those operators, but the next problem is that the library limits the number of parameters for an operator to 1 or 2 ... that you can solve by defining a function instead of an operator, which does not have those limitations:

Function ternario = new Function("ternary", 3) {
    public double apply(double... args) {
        //limitacion: no hay booleans, 0 será false y >0 sera true
        if (args[0]>0d) {
            return args[1];
        return args[2];

Operator mayorQue = new Operator(">", 2, true, Operator.PRECEDENCE_ADDITION - 1) {

    public double apply(double[] values) {
        if (values[0] > values[1]) {
            return 1d;
        } else {
            return 0d;

With what your code could be something like

double resultado=new ExpressionBuilder("ternary(30>20,3+2,(4-2)/100)")

Finally, if necessary, you could process the String received with the classic ternary operator cond ? resultado1 : resultado2 and transform it to ternary(cond,resultado1,resultado2) , but that is already outside the scope of the question.

answered by 18.07.2018 / 13:19