// The Stack ADT -- array implementation. Illustrates // how to declare, throw and catch exceptions. import java.io.*; import java.lang.RuntimeException; public interface Stack2 { public void push (int item) throws StackFullException; public int pop() throws StackEmptyException; public int size(); public boolean empty(); public boolean full(); public int ontop() throws StackEmptyException; } class StackEmptyException extends Exception { public StackEmptyException (String message) { System.out.println (message); } } class StackFullException extends Exception { public StackFullException (String message) { System.out.println (message); } } class StackADTv2 implements Stack2 { final int MAXSIZE = 100; // by default, the stack contains private int size; // 100 elements if no stack size private int[] stackADT; // is specified private int top = -1; public StackADTv2 () { size = MAXSIZE; stackADT = new int[size]; } public StackADTv2 (int inputsize) { size = inputsize; stackADT = new int[size]; } public boolean empty () { return (top == -1); } public boolean full () { return (top == size - 1); } public void push (int number) throws StackFullException { if (size() == size) throw new StackFullException ("The stack is full."); top++; stackADT[top] = number; } public int pop () throws StackEmptyException { if (empty()) throw new StackEmptyException ("The stack is empty."); int i = stackADT[top]; top--; return i; } public int ontop () throws StackEmptyException { if (empty()) throw new StackEmptyException ("The stack is empty."); int i = pop(); try { push(i); } catch (StackFullException e) { System.out.println ("The stack is full."); } return i; } public int size () { return (top + 1); } } class StackAppl2 { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); System.out.print ("Enter stack size: "); System.out.flush(); int size = Integer.parseInt(stdin.readLine()); StackADTv2 stack = new StackADTv2(size); int i = 2; /* catching two exceptions, StackFullException and StackEmptyException */ try { for (int j = 1; j <= 7; j++) { stack.push(i); System.out.println (stack.ontop() + " pushed"); i = i + 2; } } catch (StackFullException e) { System.out.println ("The stack is full."); } catch (StackEmptyException e) { System.out.println ("The stack is empty."); } System.out.println ("The current stack contains " + stack.size() + " elements."); try { for (int j = 1; j <= 7; j++) { System.out.println (stack.pop() + " poped"); } } catch (StackEmptyException e) { System.out.println ("The stack is empty."); } } }