- CS 313e
Due Monday, November 3, 2008 at 9 pm
Goal: Practice with exception handling and one-dimensional arrays.
For this project, you will write a simple array-based implementation of
a Stack. A stack is an ordered list of elements in which all insertions
and deletions are done at one end of the list, called the top of the
stack. Think of a stack of plates in the cafeteria - if you
delete/remove a plate, you remove the plate on top of the stack. If
someone adds a (hopefully clean) plate to the stack, again, they add the plate to
the top of the stack. Our stack data structure works in much the same
An array implementation of a stack is not the best way to implement a
stack, but we will gain practice with arrays and with exceptions.
In an array stk of size n that represents a stack, we will call stk the
bottom of the stack, and we will call the element with the highest
index the top element of the stack. At any given time, the stack may
not be full.
The items in your stack will be of type Object. One of your instance variables will be the array of objects.
Public interface for Stack class:
Stack(): creates an empty Stack which can hold a maximum of 50 items.
Stack(int size): creates an empty Stack which can hold a maximum of
size items. If size is not positive, create a stack that can hold a
maximum of 50 objects.
boolean empty(): tests if this stack is empty.
Object peek(): Returns object on top of this stack without removing it
from the stack. Throws an EmptyStackException if this stack is empty.
Object pop(): Removes and returns object at top of this stack. Throws an EmptyStackException if the stack is empty.
Object push(Object item): pushes item on top of this stack, and returns
item. Throws an IllegalStateException if the stack is already full.
For your StackTest class:
Create a Stack of size 10, and then push the following items: apple,
banana. Then call pop() three times. Then push: apple, banana, french
toast, wheat, cantaloupe, artichoke, ice cream, fudge, ricotta, rice a
roni, strawberry, tomato.
Your StackTest class should handle IllegalStateException and
EmptyStackException that may be thrown by Stack methods. If a stack is
full, and push() is called, the following message should be printed to
the screen: "Stack is full - item not added". If the stack is empty,
and pop() or peek() is called, the following message should be printed
to the screen: "Stack is empty - could not carry out operation".
What is listed above is not a complete test of the Stack class. Add to
the described tests so that you test all the functionality of your
You must submit Stack.java and StackTest.java by 11 pm on the due date.