# 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

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[0]>0d) {
return args[1];
}
return args[2];
}
};

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

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

With what your code could be something like