sutoL
sutoL

Reputation: 1767

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 infix evaluation, and I am wondering if brackets can be used with either of these methods?

Upvotes: 3

Views: 2812

Answers (2)

bjg
bjg

Reputation: 7477

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

Upvotes: 0

polygenelubricants
polygenelubricants

Reputation: 383676

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


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

Upvotes: 5

Related Questions