Untitled

 avatar
unknown
plain_text
a year ago
1.5 kB
5
Indexable
public class Stack {
    private int capacity;
    private int[] stackArray;
    private int top;

    public Stack(int capacity) {
        this.capacity = capacity;
        this.stackArray = new int[capacity];
        this.top = -1;
    }

    public void push(int item) throws StackFullException {
        if (top == capacity - 1) {
            throw new StackFullException("Stack is full. Cannot push more items.");
        }
        stackArray[++top] = item;
    }

    public int pop() throws StackEmptyException {
        if (top == -1) {
            throw new StackEmptyException("Stack is empty. Cannot pop from an empty stack.");
        }
        return stackArray[top--];
    }

    public static void main(String[] args) {
        try {
            Stack myStack = new Stack(3);
            myStack.push(1);
            myStack.push(2);
            myStack.push(3);
            myStack.push(4); // Raises StackFullException
        } catch (StackFullException e) {
            System.out.println(e.getMessage());
        }

        try {
            Stack myStack = new Stack(3);
            myStack.pop(); // Raises StackEmptyException
        } catch (StackEmptyException e) {
            System.out.println(e.getMessage());
        }
    }
}

class StackFullException extends Exception {
    public StackFullException(String message) {
        super(message);
    }
}

class StackEmptyException extends Exception {
    public StackEmptyException(String message) {
        super(message);
    }
}
Editor is loading...
Leave a Comment