Day 2: Postfix Expression Evaluation


Exercise

Write a Java program to compute the value of an arithmetic expression written in postfix notation.

Introduction

Postfix notation, also known as Reverse Polish notation or RPN, is a method of writing arithmetic and algebraic expressions in which all operators follow their operands (contrast this with infix notation, the more familiar method). For example:

4 6 + 12 3 / 4 + 5 28 14 - * 2 / 49 7 / +

These expressions would be written in infix as:

4 + 6 12 / 3 + 4 5 * (28 - 14) / 2 + (47 / 7)

The primary advantage to using postfix notation is there is no need to explicitly describe precedence using parentheses. This simplifies machine evaluation significantly.

Machine evaluation is done using a structure known as a stack. The stack structure implements an idea know as Last In First Out (LIFO). This means, simply, the last object added is the first object to be removed. Objects are added (pushed) and removed (popped) from only one end of the stack. An analogy for a stack is a literal stack of papers, but you can only put papers on the top of this stack. Likewise, you can only take papers off the top of the stack.

Algorithm

  1. Familiarize yourself with the postfix algorithm.
  2. Implement the core functionality using a text-based interface for I/O.
  3. Build a GUI to wrap your implementation.

Resources

Hints


Return Home