-1

I'm trying to create a simple natural language calculator, and currently have managed to convert all operands into doubles and operators into the chars '+', '-', '*', '/', '%'.

However, I want to evaluate the expression using the correct order of operations, and to that end it would be useful if I could take advantage of Java's natural order of operations when computing expressions. Is there a way to compute this sort of expression that contains character operands? I was thinking that maybe my program could write some sort of temporary java class, compile it and run it to evaluate the expression, but that seems a tad excessive. There must be a simpler way to do it?

a3onstorm
  • 406
  • 5
  • 13
  • 2
    Have you heard about Reverse Polish Notation? – gaborsch Mar 18 '14 at 20:15
  • I've heard of it but I don't know too much about it. How would it be useful in this situation? Wouldn't I have to parse through the expression to get it into postfix notation? – a3onstorm Mar 18 '14 at 20:25
  • 1
    You can transform your infix expression into a postfix expression (RPN) (e.g by the recommended Shunting-yard algorithm), then evaluate it. – gaborsch Mar 18 '14 at 20:27

2 Answers2

2

There's no way to use "Java's natural order of operations", as this is implemented by the compiler, and you're working at runtime. You could use the ScriptEngine to do the whole calculation for you. Otherwise you would have to implement your own expression parser, using say recursive descent, which is pretty easy, or Dijkstra's Shunting-yard algorithm.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

The following link shows how can you evaluate math expressions given as String: Evaluating a math expression given in string form

So you can concatenate the operators with double to create mathematical equation String and evaluate using the ScriptEngine as shown in above link. The precedence followed can be changed by using parenthesis appropriately.

Community
  • 1
  • 1
Sourabh Bhat
  • 1,793
  • 16
  • 21