简体   繁体   中英

Building a math expression parser/evaluator?

I am trying to build my own math expression parser in Java ,I know that there are many script managing engines out there.But I wanted to build my own ,just for parcticing.

However, I've been finding difficulties in progressing. so I began to think if there is a better way of writing it. Here is how I am doing it:

(in the meantime I'm assuming that the input is legal) The only legal operators are: + - * / ^ ( )

I get a String expression input from the user. Then I start looping throgh the string input to seek "(" if I found one I calculate the value of the value inside it then replace the sub expression string with the result.

Should I continue to program it this way or should I take another approach? Are there any tutorials that explain how to accomplish this (not the code - just the theory in general)?

Any help is appriciated.

You should look into the Shunting Yard Algorithm , which allows you to parse algebraic expressions including operator precedence and parentheses.

Also, you might be interested in Abstract Syntax Trees to represent the result of the parsed expression, on which you can do further work, as pretty printing and evaluating the expression.

You will probably want to make a recursive descent parser , which is the standard way to parse reasonably simple languages. Essentially, it's a more structured way of implementing the "search for parenthesis and evaluate expression inside it" approach that you are describing. Make sure that you are comfortable with recursion before you start, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM