ICS 211 Homework 10

Stack Calculator

0. Goals and Overview

The goal of this assignment is to use a stack to build a simple stack-based calculator.

1. Simple Calculator (100%)

A simple stack-based calculator works as follows:

Because the operator is entered after the operands, this kind of calculator is called a postfix calculator.

Pay attention to the order of the operands. If 5 and 3 are pushed onto the stack, 3 is at the top of the stack and is popped first when an operator is entered. If the operator is -, make sure your code computes 5 - 3 = 2, rather than 3 - 5.

You may design any user interface for your calculator that you wish. The simplest user interface is to read operands and operators from the terminal, but implementations with a nicer user interface are also fine.

Because a postfix calculator calculates immediately as soon as an operand is entered, your calculator has no need for an "=" operator such as found on a regular calculator. If your user interface is the terminal, the "=" operator can be used to tell the calculator to exit.

If the user enters an operator when there is 0 or 1 values on the stack (instead of 2 or more), the calculator should print an appropriate message and continue, without changing the stack.

Your calculator should run with either a Java Standard Library Stack or a stack that you define, perhaps based on the instructor's code.

2. Example calculations

The user inputs here are given one per line, with the output from your calculator indented for clarity.

2
2
+
   4

The final result, 4, is the only element left on the stack.

2
2
+
   4
3
*
   12
22
20
-
   2
/
   6
4
%
   2
8
^
   256

The initial result, 4, is the only element left on the stack after the +. Then we multiply 3 by 4 to give 12, which again is the only element left on the stack. After pushing 22 and 20, 20 is at the top of the stack, with 22 below it and 12 at the bottom of the stack. The - operator computes 22 - 20 to give 2, leaving 2 at the top of the stack and 12 below it. The next operator, /, computes 12 / 2 giving 6 as the only value on the stack. The user next enters 4 and modulo, so your calculator pops 4 and 6, computes 6 % 4 = 2, and pushes 2 onto the stack. The final operation computes 2^8 = 256.

Details of your own output may be different, as long as you print the correct result. For example, you are welcome to print the entire stack at the end of each operation. Also, since values are doubles, your results may be printed with fractional digits, for example 6.0000.

Turning in the Assignment

Use Laulima to turn in your StackCalculator.java and any other files that your code requires.