To get some practice using stacks, implement a reverse-polish notation calculator (like we saw in class) using java.
3
2
+
5
*
=
After each command you can have the calculator print out what's at the top of the stack without popping it. Or you can have the program print out the entire stack (this is not what calculators usually do, but will help you debug). If the user enters "=", this pops the number off the top of the stack and also prints it out. The code should print out an error if the user tries to do an operation when the stack is empty.
Java has the stack as a built-in type. You use it by including java.util.* in your code. Here is a link to the API of the stack class in Java, look it over and try to understand what kind of information is being given to you here.
http://java.sun.com/j2se/1.3/docs/api/java/util/Stack.html
We are providing you with the Calulator.java file as a starting point for the problem.
Here is the link to the API for Java's StringTokenizer class:
http://java.sun.com/j2se/1.3/docs/api/java/util/StringTokenizer.html
An example of processing "words" using StringTokenizer
Stack myStack = new Stack();
String line = "Mary had a litte lamb";
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String token = st.nextToken();
myStack.push(token);
}
Be aware though that the items in your Stack are now all of type String. For the Calculator, you will need to cast the numbers back into type int after you pop them. Another way to do this is to add code in the while loop above to convert your String tokens to objects of type Integer (unless it is an operator like '+' or '=').
if the input is
a +, then
a *, then
an =, then
get the input
an integer,
push it on the stack
res = pop();
res = res + pop();
push res;
print res;
res = pop();
res = res * pop();
push res;
print res;
res = pop();
print res;