# Calculable. Expressions with conditionals

3

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) {
e.printStackTrace();
} catch (UnparsableExpressionException e) {
e.printStackTrace();
}
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
source

## 1 answer

2

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

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) {
@Override
public double apply(double... args) {
//limitacion: no hay booleans, 0 será false y >0 sera true
if (args>0d) {
return args;
}
return args;
}
};

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

@Override
public double apply(double[] values) {
if (values > values) {
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)")
.operator(mayorQue)
.function(ternario)
.build().evaluate();
``````

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
source