simple calculator in java parser
I am currently making a simple calculator parser in Java, to deal only with + and - operators, and whole numbers. I have read about postfix and i开发者_如何转开发nfix evaluation, and I am wondering if brackets can be used with either of these methods?
The beauty of the postfix/prefix notation is that you do NOT need the brackets. Brackets are used in infix notation because there are ambiguities, e.g:
a + b - c
This can mean either of the following:
(a + b) - c
a + (b - c)
However, in postfix notation, they are clearly different:
a b + c -
a b c - +
There is no need for parantheses/brackets to enforce evaluation order in postfix notation.
See also
- Wikipedia/Reverse Polish Notation
Conversion from infix
You can take an expression in infix notation with parantheses and convert it to postfix notation, obeying operator precedence. One such algorithm is Edsger Dijkstra's stack-based "shunting-yard algorithm".
See also
- Wikipedia/Shunting-yard algorithm
If you are only concerned with the simple math operators + and - which are commutative then you probably do not need to care about parenthesis which usually enforce the order of computation.
Your calculator might only need to be a simple parser and accumulator that ignores parenthesis if present - unless I'm missing something about the intended meaning of the parenthesis
精彩评论