Click here to Skip to main content
15,566,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good morning,
I would like to know how I can check if a stack is empty and in that case throw an exception. The idea is to have a main class, and other classes that do the tests.

Thank you,
Luke


What I have tried:

Class Stack

Java
    public class Stacks{

    public static int max(Stackstack) throws isEmpty {
        int max = (int) Integer.MIN_VALUE;
          if (stack.isEmpty()) {
            throw new isEmpty("The stack is empty");
          }
         else {
            return max;
          }
        } 
}


Class test1
Java
public class Test1{

    public static void main(String[] args) throws IncorrectOperation {

        Stack stack= new LinkedStack();

        try {
            System.out.println(stack);
            System.out.println(Stacks.max(stack));
        } catch (IncorrectOperation e) {
            e.printStackTrace();
        }

    }

}


Class LinkedStack
Java
public class LinkedStack implements Stack{

    private Node top;

    public LinkedStack() {
        top= null;
    }

    public void push(Object element) {
        Node node = new Node(element);
            node.setLink(top);
        top= node;
    }

    public void pop() throws BottomOverflow{
        if (isEmpty()) {
            throw new BottomOverflow("Impossible pop");
        }
        top= top.getLink();
    }

    public Object top() throws BottomOverflow{
        if (isEmpty()) {
            throw new BottomOverflow("Impossible to consult the top");
        }
        return top.getElement();
    }

    public boolean isEmpty() {

        return (top== null);
    }
}
Posted
Comments
Richard MacCutchan 7-Nov-20 10:53am    
What is the problem?
Lucas Dana 7-Nov-20 13:20pm    
How can I throw an exception in Java when it checks if a stack is empty, and if it is not, show me the elements of that stack and the highest number.?
Richard MacCutchan 7-Nov-20 13:50pm    
You already do that in your code. So what exactly is the problem?
Lucas Dana 7-Nov-20 13:22pm    
public static int max(Stack stack) throws IncorrectOperation{


}

}
Lucas Dana 7-Nov-20 13:24pm    
What code should I put in so that it throws the exception in case the stack is empty, and in another test it returns the elements of the stack and the integer with the maximum value?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900