I'm trying to write a Java routine to evaluate simple math expressions from String
values like:
"5+3"
"10-40"
"10*3"
I want to avoid a lot of if-then-else statements. How can I do this?
I'm trying to write a Java routine to evaluate simple math expressions from String
values like:
"5+3"
"10-40"
"10*3"
I want to avoid a lot of if-then-else statements. How can I do this?
It is possible to convert any expression string in infix notation to a postfix notation using Djikstra's shunting-yard algorithm. The result of the algorithm can then serve as input to the postfix algorithm with returns the result of the expression.
I wrote an article about it here, with an implementation in java
With JDK1.6, you can use the built-in Javascript engine.
Try the following sample code using JDK1.6's Javascript engine with code injection handling.
Another way is to use Spring Expression Language or SpEL which does a whole lot more along with evaluating mathematical expressions therefore maybe slightly overkill. You do not have to be using Spring framework to use this expression library as it is stand-alone. Copying examples from SpEL's documentation:
Read more concise SpEL examples here and the complete docs here
if we are going to implement it then we can can use the below algorithm :--
While there are still tokens to be read in,
1.1 Get the next token. 1.2 If the token is:
1.2.1 A number: push it onto the value stack.
1.2.2 A variable: get its value, and push onto the value stack.
1.2.3 A left parenthesis: push it onto the operator stack.
1.2.4 A right parenthesis:
1.2.5 An operator (call it thisOp):
While the operator stack is not empty, 1 Pop the operator from the operator stack. 2 Pop the value stack twice, getting two operands. 3 Apply the operator to the operands, in the correct order. 4 Push the result onto the value stack.
At this point the operator stack should be empty, and the value stack should have only one value in it, which is the final result.