I have 2 arrays :
int[] values = {1, 2, 3, 4, 5, 6};
int[] operators = {PLUS, MINUS, MULTIPLY, MINUS, DIVIDE, PLUS}
UPPERCASE words in brackets are defined constants.
i want to use corresponding operators (+, -, *, /, +) to evaluate the values in the values array
:
1 + 2 - 3 * 4 / 5 + 6 = 1 + 2 - (3*4/5) + 6 = 6.6 // expected result
i have created a method (with a switch case
), based on the above constants to know wich operators i should use.
public static int evaluate(int a, int b, int op) {
int result = 0;
switch (op) {
case PLUS:
result = a + b;
break;
case MINUS:
result = a - b;
break;
/* .... */
}
return result;
}
But as you see, with this method the result will be wrong: that's why when executed i got :
1+2-3*4/5+6 = ((((1+2)-3)*4)/5)+6 = 0*4/5+6 = 0 / 5 + 6 = 0 + 6 = 6 // not the expected result
somebody can help me ?
SOLUTION : JEval
@AudriusMeškauskas's link contains a list of (powerful) libraries. I read JEval
features, i tested it an i it works like a charm !
Evaluator evaluator = new Evaluator();
System.out.println("eval : " + evaluator.evaluate("1 + 2 - 3 * 4 / 5 + 6"));
output : 6.6