Question: Write a Java program that uses a stack to evaluate postfix expressions . Your program takes a postfix expression as an input (for example, 3
Write a Java program that uses a stack to evaluate postfix expressions.
Your program takes a postfix expression as an input (for example, 3 42 + 5 * ) from the user and calculates/display the result of the expression. You may use the following algorithm.
Algorithm to evaluate a postfix expression:
While the end of the postfix expression has not been reached
Read the next token from the postfix expression
If the token is a number
Push the token onto the stack
Else // token must be an operator
Pop an element from the stack // operand 2
If operand2 is 0 and the token is a division or modulus operator
Output error // Division by zero
Stop
(end if)
Pop another element from the stack // operand 1
Perform the operation
Push the result of the operation onto the stack
(end else)
(end while)
Pop the stack // the popped element is the answer
(Extra 5points) Make a loop to keep entering postfix expressions until the user stops.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
