我需要從數組中填充堆棧,然後按順序打印出元素,然後再次顛倒順序。我遇到的問題是我得到一個ArrayIndexOutOfBoundsException並且不知道它來自哪裏。我已經嘗試通過調試運行,它看起來像彈出元素永遠不會到達最後一個元素。下面是我的代碼:java stack從數組中讀取ArrayIndexOutOfBoundsException
public class arrayStack {
private int top;
private String[] storage;
public arrayStack(int capacity)
{
storage = new String[capacity];
top = -1;
}
public boolean isEmpty() {
return (top == 0);
}
String peek() {
return storage[top];
}
String pop() {
top--;
return storage[top];
}
public void push(String str) {
top++;
storage[top] = str;
}
}
StackMain.java:
public class StackMain {
public static void main(String[] args) {
//int j = 5;
String[] list = new String[5];
list[0] = "Beware";
list[1] = "The";
list[2] = "Ides";
list[3] = "Of";
list[4] = "March";
arrayStack stack = new arrayStack(5);
for(int i = 0; i < list.length; i++)
{
stack.push(list[i]);
}
for(int j = 0; j < list.length; j++)
System.out.println(stack.pop());
}
}
非常感謝你,這是一個簡單的答案,我已經奮鬥了整個下午更靈活的協議棧實現。 – user519670 2012-02-29 02:22:40