COMP 2100 Lab Exercise 6: Stack-Based Postfix-to-Infix
Converter
(10 points)
Turn in before the next lab period
We are accustomed to writing arithmetic expressions using infix notation. This means that operators requiring two operands are written with the operator in the middle, e.g. 12 + 27 for addition. In expressions involving multiple operations, we sometimes need to use parentheses to override operator precedence. For example: 2 + 3 * 4 always yields 14 instead of 20 because multiplication takes precedence over addition. To get the result 20, we need to write it as ( 2 + 3 ) * 4.
The need for parentheses is eliminated if we write the expression using either prefix or postfix notation. In prefix notation, an operator precedes both its operands, e.g. + 12 27 and in postfix notation, an operator follows both its operands, e.g. 12 27 +. In this exercise we will focus on postfix notation.
Using postfix notation, 2 + 3 * 4 would be written as 2 3 4 * + and ( 2 + 3 ) * 4 would be written as 2 3 + 4 *. They are distinct and no parentheses are needed.
An infix expression can be converted to postfix using a stack. Similarly, a postfix expression can be converted to infix using a stack. For the latter, parentheses need to be introduced to the expression instead of removed from it. A pseudocode algorithm for postfix-to-infix conversion is described below.
Algorithm for postfix-to-infix conversion |
---|
Create a stack called symbolStack For each token in a left-to-right scan of the expression { if (current token is an operator) { pop an operand from the symbolStack pop an operand from the symbolStack form an infix expression from the operator and operands parenthesize the infix expression push the infix expression on the symbolStack } else { // token is an operand push the token onto the symbolStack } } pop the expression from the symbolStack |
Your assignment is to write a postfix-to-infix converter based on the algorithm described above. The zip file ex6.zip contains three Java files: PostfixToInfixConverter.java (the class you will work with), PostfixToInfixConverterTest.java (a driver class for testing), and Operators.java (a handy utility described below). All your work will be in PostfixToInfixConverter.java.
Maximum 8 points without exception handling (Implementation Note 6), 10 points with exception handling.