Stacks are used by compilers to help in the process of evaluating expressions and generating machine-language code. In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses.
Humans generally write expressions like 3 + 4 and 7 / 9 in which the operator (+ or / here) is written between its operands—this is calledinfix notation. Computers prefer postfix notation, in which the operator is written to the right of its two operands. The preceding infix expressions would appear in postfix notation as 3 4 + and 7 9 /, respectively.
To evaluate a complex infix expression, a compiler would first convert the expression to postfix notation and evaluate the postfix version. Each of these algorithms requires only a single left-to-right pass of the expression. Each algorithm uses a stack object in support of its operation, but each uses the stack for a different purpose.
In this exercise, you will write a Java version of the infix-to-postfix conversion algorithm. Write a class InfixToPostfixConverter to convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers such as
(6 + 2) * 5 - 8 / 4
to a postfix expression. The postfix version of the preceding infix expression is (note that no parentheses are needed)
6 2 + 5 * 8 4 / -
The program should read the expression into StringBuilder
infix
and use the stack class implemented in this chapter to help create the postfix expression in StringBuilder
postfix
. The algorithm for creating a postfix expression is as follows:
(
on the stack.)
to the end of infix.While the stack is not empty, read infix from left to right and do the following:
If the current character in infix is an operator:
If the current character in infix is a right parenthesis:
The following arithmetic operations are allowed in an expression:
+ addition
- subtraction
* multiplication
/ division
^ exponentiation
% modulus (same precedence as division)
Some of the methods you may want to provide are a follows:
public String convertToPostfix(String infix)
, which converts the infix expression to postfix notation.public boolean isOperator(char c)
, which determines whether c
is an operator.public boolean precedence(char op1, char op2)
, which determines whether the precedence of operator1 (from the infix expression) is less than, equal to or greater than the precedence of operator2 (from the stack). The method returns true if operator1 has lower precedence than operator2. Otherwise, false is returned.