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
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; } } }
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(); } } }
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); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)