Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are multiple issues with your code:</p> <ol> <li>You never initialize the variable <code>STACKSIZE</code>. It is an int so it just <em>happens</em> to default to zero. It has this value of zero when you first initialize your storage array.</li> <li>Your <code>setStackSize</code> method changes the <code>STACKSIZE</code> value, but it does nothing with the internal storage array (doesn't attempt to resize it).</li> <li>In any case, since you initialize an empty array in your constructor, you can never add any elements to it, this is why you get an ArrayOutOfBoundsException.</li> </ol> <p>These are all coding errors, but you have some conceptual errors as well.</p> <ol> <li>You haven't decided wether you want a stack that has an initial fixed size, or one that dynamically grows. And because of this you are mixing both concepts in your code and it is causing bugs.</li> </ol> <p>If you decide to go with a fixed size array then you can adjust your class to be more like this:</p> <pre><code>public class Stack { private int[] storage; private int size; public Stack(int capacity) { super(); storage = new int[capacity]; } public void push(int number) { if(storage == null) return; if(size &gt;= storage.length) throw new RuntimeException("Stack Overflow"); storage[size] = number; ++size; } public int pop() { if(storage == null) throw new RuntimeException("No storage"); if(size == 0) throw new RuntimeException("Stack Underflow"); --size; return storage[size]; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload