package examples.stack1; /** * Author: W. M. Farmer
* Revised: February 11, 2007
*
* Description: Implements a stack as an array. */ public class Stack { private static final int MAX = 1000; private static int[] stack_ = new int[MAX]; private static int height_ = 0; /** * Selector that gets the top element of the stack. * * @return top element of the stack */ public static int top() { if (height_ != 0) return stack_[height_ - 1]; else { System.out.println("Error in top(): Stack is empty."); return 0; } } /** * Selector that gets the height of the stack. * * @return height of the stack */ public static int height() { return height_; } /** * Mutator that pushs an element onto the stack. * * @param element value to be pushed onto the stack */ public static void push(int element) { if (height_ != MAX) { stack_[height_] = element; height_ = height_ + 1; } else System.out.println("Error in push(" + String.valueOf(element) + "): Stack is empty."); } /** * Mutator that pops the stack. */ public static void pop() { if (height_ != 0) height_ = height_ - 1; else System.out.println("Error in pop(): Stack is empty."); } /** * Prints the contents of the stack. */ public static void print() { String s; s = "Stack contents: ["; for (int i = 0; i < height_; i++) { if (i + 1 == height_) s = s + String.valueOf(stack_[i]); else s = s + String.valueOf(stack_[i]) + ","; } s = s + "]."; System.out.println(s); } }