我有一个ArrayIndexOutOfBoundsException的问题,它总是出现在我的程序中。我怎样才能尝试{}?OutOfBoundsException到堆栈
@Override
public Object pop() {
if (stackIsEmpty()) {
System.err.println("underflow");
return null;
} else {
try {
Object temp = stack[top];
stack[top--] = null;
System.out.println("top is " + top);
return temp;
} catch (ArrayIndexOutOfBoundsException e) {
return "exception";
}
}
}
加入其余类的代码(I与-1()中的比较成stackisEmpty):
public class ArrayStackImpl implements ArrayStack {
private int top = -1;
private int maxLength;
public Object stack[] = new Object[maxLength];
public ArrayStackImpl(int maxLength) {
this.maxLength = maxLength;
}
@Override
public boolean stackIsEmpty() {
return (top < 0);
}
@Override
public void push(Object o) {
if ((top >= maxLength - 1))
System.err.println("overflow");
else
try {
stack[++top] = o;
} catch (ArrayIndexOutOfBoundsException e) {
}
}
我有一种感觉,'top'是-1。执行堆栈时出现经典错误。 – Maroun 2014-10-07 12:33:47
你应该包括整个班级。特别是构造函数,'top'和'stack'以及'push'方法的初始化。 – Eran 2014-10-07 12:34:51
如果我会做到0,它不会改变。我试过 – jenius 2014-10-07 12:35:34