Lab 5: Stacks
Due: Thursday, Feb. 25, 11:59pm
This lab will give you more experience with writing and testing data structures (this time a stack). We'll also practice writing method signatures, generics, and throwing exceptions. This lab is individual and everyone should submit their own code and typescript, but you are welcome to discuss and compare code with your classmates.
To start, make a new lab5 project and create or add the following files:
In this lab you will write a constructor and four methods inside the Stack class.
First spend some time thinking about what fields you might need (which may change as you continue implementing the stack). Then write these fields and a default constructor (creates an empty stack) that handles each one.
Write a method "push", which should add an element to the stack. What arguments should this function take in? What should it return? Should it be public, private, static?
Write a method "pop", which should return the top element from the stack and decrease the number of elements in the stack by one. Again think about the method signature. What should happen if the stack is empty? In this case, throw a RuntimeException.
To create a new runtime exception, usually it is best to start with the second constructor, which takes in a message. Write an informative message to the stack user to tell them what went wrong.
Write a method "peek", which allows the user to observe the top element on the stack, but it doesn't "pop" (remove) the element.
Write a method "empty", that returns whether or not the stack is empty. What should the return type of this method be?
script java StackTester exit
import java.util.Stack;
Make sure to change it back afterwards (remove the import statement) so that you code is based on your own stack class.
If you have more time, you can either write a copy constructor for your stack, or you may begin work on Homework 5.