The aim of this exercise is to familiarise yourself with the use of constructors, arrays, exceptions and to gain experience in using a couple more handy Java classes.
Your task is to build a Stack class similar to the one you used to implement your postfix calculator. It will be of a fixed size (MAX_STACK) and should include the following data members:
private int size; private Object items[] = new Object[ MAX_STACK ];
It should provide the following methods:
public Stack() public void push( Object item ) public Object pop() public Object peek() public boolean empty() public boolean full() public String toString() public removeAllElements()
In this exercise size is the number of elements in the stack (and points at the next location to enter an element since Java arrays start at element 0) and items holds the elements on the stack.
For this exercise you should assume that the functions act as defined below:
You should complete the specification, design and implement the Stack class and undertake testing on the completed class.
Before you leap into the code, you should sit back and write a high level description of the class and a detailed specification of each of the operations. In particular you should think about error conditions (e.g. what happens if you try to pop an element from an empty stack?).
Once you've written and tested it, replace the Stack class you used in your calculator with the one that you've
just written (by not importing the java.util one). Does it work?
Unlike your stack, the java.util.Stack doesn't have a fixed size, so if you want to throw a FullStackException you'll have to make your own. To do this, you can save this chunk of code to a file called FullStackException.java:
/** * This exception should be thrown when an operation on * a stack doesn't succeed because the stack is already * full to capacity. * * @author (c) Andy Wood ... 1997 * **/ public class FullStackException extends RuntimeException { public FullStackException() { super(); } }