001package algs13;
002import stdlib.*;
003public class XFixedCapacityStackOfStringsWithStaticMember {
004        private static int numStacks = 0;
005        public  static int numStacks() { return numStacks; } 
006        private int stackId;
007        private int stackId() { return stackId; }
008
009        private String[] a; // holds the items
010        private int N;      // number of items in stack
011        // Invariant (after the constructor):
012        //   a[0]..a[N-1] are non null
013        //   a[N]..a[a.length-1] are null
014        public XFixedCapacityStackOfStringsWithStaticMember (int capacity) {
015                this.stackId = numStacks++;
016                this.a = new String[capacity];
017                this.N = 0;
018        }
019        public int size ()        { return N; }
020        public boolean isEmpty () { return (N == 0); }
021        public void push (String item) {
022                if (item == null) throw new IllegalArgumentException ();
023                if (N >= a.length) throw new RuntimeException ("Stack full");
024                a[N] = item;
025                N++;
026        }
027        public String pop () {
028                if (N <= 0) throw new RuntimeException ("Stack empty");
029                N--;
030                String result = a[N];
031                a[N] = null;
032                return result;
033        }
034
035        public static void main(String[] args) {
036                //Trace.showObjectIdsRedundantly (true);
037                //Trace.showBuiltInObjects (true);
038                Trace.drawSteps();
039                //Trace.drawStepsOfMethod ("main");
040                //Trace.drawStepsOfMethod ("printPop");
041                Trace.run ();
042                XFixedCapacityStackOfStringsWithStaticMember stack1 = new XFixedCapacityStackOfStringsWithStaticMember (7);
043                XFixedCapacityStackOfStringsWithStaticMember stack2 = new XFixedCapacityStackOfStringsWithStaticMember (3);
044                stack1.push ("a");
045                stack2.push ("b");
046                stack1.push ("c");
047                stack2.push ("d");
048                stack1.push ("e");
049                stack2.push ("f");
050                stack1.push ("g");
051                printPop(stack2);
052                printPop(stack1);
053        }
054        private static void printPop (XFixedCapacityStackOfStringsWithStaticMember s) {
055                int id = s.stackId();
056                int num = XFixedCapacityStackOfStringsWithStaticMember.numStacks();
057                StdOut.printf("Stack %d of %d:\n", id, num);
058                while (!s.isEmpty()) {
059                        StdOut.println (s.pop ());
060                }
061        }
062}