Question
Description Write a program that uses a stack to add, subtract multiply, and divide. Many virtual machines, like the JVM, are based on the notion
Description
Write a program that uses a stack to add, subtract multiply, and divide. Many virtual machines, like the JVM, are based on the notion of a run-time stack to hold operands and operators. This is like a stack of plates where operands/operators may only be added to or removed from the top. A program in this stack-language looks like the following.
PUSH 1 PUSH 2 ADD RESULT => 3 (output from stack)
To interprete this code, consider the following.
PUSH 1 pushes a 1 onto the stack and PUSH 2 pushes a 2 onto the stack, which means the stack has two elements and looks like the following.
2 (top of stack) 1
ADD removes the top 2 values on the stack, adds them and pushes the result (so the 2 and 1 would be replaced by 3).
RESULT is a special operation that will display the current value at the top of the stack.
Write an interpreter for a stack machine that has the following operations: PUSH, ADD, SUB, MUL, DIV, and RESULT. The data values and operations are integer.
Input
The input will be N lines of stack code where the Nth line contains the letter R.
Output
There will be one line of output, which is the value computed by the stack machine program.
Sample Input - Example 1
P 1 P 2 A P 3 M P 1 S P 2 D R
Sample Output - Example 1
=> 4
Sample Input - Example 2
P 1 P 2 P 3 P 4 P 5 M A P 6 S A A P 10 D R
Sample Output - Example 2
=> 2
Additional Information
You should use a Scanner to read the input values.
Do not prompt for input. The input will be there.
You should use System.out.println() to generate your output.
The output line has to match exactly.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started