Implement a very simple array-based Stack class whose objects represent stacks o
ID: 3730185 • Letter: I
Question
Implement a very simple array-based Stack class whose objects represent stacks of integer.
Below is the outline for your Stack class and associated FullStackException class
public class Stack {
// a public static constant MAZSIZE initialized to 100
// an array of int of size MAXSIZE to store the values
// a private int to store the stack's size
// an isEmpty() method that returns true iff the stack is empty (size == 0)
// an isFull() method that returns true if the stack if full (size == MAXSIZE)
// a pop method to pop the stack or throw an EmptyStackException (in java.util)
// a push method to push a value onto the stack or throw a FullStackException (see below)
// a top() method to return the top of the stack or throw an EmptyStackException
// a getSize() method
}
public class FullStackException extends RuntimeException {
// default constructor calls RuntimeException constructor with "Can't push onto full stack."
}
Explanation / Answer
public class Stack { // a public static constant MAZSIZE initialized to 100 public static final int MAXSIZE = 100; // an array of int of size MAXSIZE to store the values private int[] arr; // a private int to store the stack's size private int size; public Stack() { arr = new int[MAXSIZE]; size = 0; } // an isEmpty() method that returns true iff the stack is empty (size == 0) public boolean isEmpty() { return size == 0; } // an isFull() method that returns true if the stack if full (size == MAXSIZE) public boolean isFull() { return size == MAXSIZE; } // a pop method to pop the stack or throw an EmptyStackException (in java.util) public int pop() { if(isEmpty()) { throw new EmptyStackException(); } int val = top(); size--; return val; } // a push method to push a value onto the stack or throw a FullStackException (see below) public void push(int val) { if(isFull()) { throw new FullStackException(); } arr[size++] = val; } // a top() method to return the top of the stack or throw an EmptyStackException public int top() { if(isEmpty()) { throw new EmptyStackException(); } return arr[size-1]; } // a getSize() method public int getSize() { return size; } } public class FullStackException extends RuntimeException { // default constructor calls RuntimeException constructor with "Can't push onto full stack." public FullStackException() { super("Can't push onto full stack."); } } public class EmptyStackException extends RuntimeException { // default constructor calls RuntimeException constructor with "Can't push onto full stack." public EmptyStackException() { super("Can't push onto full stack."); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.