我有一个定制的 Stack 类,它不操作数组,但是ArrayList<String>
.
我的 Stack 类有 push、pop 和 size 方法。
我正在通过索引实例变量跟踪索引。
我创建了一个数组来保存三个元素。
这三个元素被压入堆栈。最后,最后一个元素被弹出并打印在控制台上。
我总是收到自定义 StackIsUnderflowing() 异常。
谁能告诉我错误在哪里?
import java.util.ArrayList;
class StackIsUnderflowing extends Exception {
private static final long serialVersionUID = 1 L;
public StackIsUnderflowing() {
super("Stack Underflowing");
}
}
//main Stack class
public class Stack {
private int index;
//List of String literals
private ArrayList < String > aStackArr = new ArrayList < String > ();
private static int ZERO = 0;
//constructor
public Stack() {
this.index = -1;
}
//return the size
public int size() {
return aStackArr.size();
}
//push value on to Stack add value to List of String input variable
public void push(String anInt) {
index = aStackArr.size() - 1;
aStackArr.add(anInt);
System.out.println(index + aStackArr.get(index));
}
//pop values from input variable
public String pop() {
try {
if (index < Stack.ZERO) {
throw new StackIsUnderflowing();
} else {
String result = aStackArr.remove(index);
index = aStackArr.size() - 1;
return result;
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.exit(-1);
return "-1";
}
}
//peek into LIFO top input literal
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack aStack = new Stack();
String[] names = new String[3];
names[0] = "ll";
names[1] = "cc";
names[2] = "dd";
String tmp;
for (int i = 0; i < aStack.size(); ++i) {
System.out.println(names[i]);
aStack.push(names[i]);
}
tmp = aStack.pop();
System.out.println(tmp);
}
}