1

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

S.Thiongane
  • 6,883
  • 3
  • 37
  • 52

2 Answers2

2

Edsger Dijkstra published a solution to this in 1961. It's called the Shunting Yard Algorithm. A copy of the original paper is available here (pdf), in case you're interested. It takes into account the precedence of the operators, rather than simply computing from left to right, as your original solution did. I suspect the Evaluator class uses some variation on the Shunting Yard Algorithm to properly compute the solution.

andand
  • 17,134
  • 11
  • 53
  • 79
0

Replace all temporary values with calculated results fo multiplication and division and at the end add/substarct rest.

The problem is not at this part of the source code and you have expand your application.

Your solution adds/substracts/multiplies/divides next number with previous result. You have to modify the method of calculations.

Example:

Simple calculator

Pawel
  • 1,457
  • 1
  • 11
  • 22
  • You can change the variables to doubles. They are better if you use the division, but this is not main problem in your application. – Pawel Aug 30 '13 at 19:36
  • yes i know i am wrong with my method. Pliz can you give an example ? don't forget that you can have more than 20 values in the array !! – S.Thiongane Aug 30 '13 at 19:39
  • Link to calculator written in java is above, in my answer. – Pawel Aug 30 '13 at 19:44
  • You do not need to store temporary results in the table;). Replace actual numbers with the result of multiplication/division. – Pawel Aug 30 '13 at 19:51