2014-10-07 60 views
0

我有一个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()中的比较成s​​tackisEmpty):

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) { 
      } 
    } 
+0

我有一种感觉,'top'是-1。执行堆栈时出现经典错误。 – Maroun 2014-10-07 12:33:47

+1

你应该包括整个班级。特别是构造函数,'top'和'stack'以及'push'方法的初始化。 – Eran 2014-10-07 12:34:51

+0

如果我会做到0,它不会改变。我试过 – jenius 2014-10-07 12:35:34

回答

1

关于弹出非空堆栈top可能会变为-1(对于“空堆栈”)。所以

private int top = -1; 

public boolean stackIsEmpty() { 
    return top < 0; // != -1 
} 

不要在你的构造领域的初始化。在此之前,maxlength未初始化,并且为0。 此外,您不需要maxlength作为字段。 stack.length == maxlength

public Object[] stack; 

public ArrayStackImpl(int maxLength) { 
    stack = new Object[maxLength]; 

(I所用的更传统的符号Object[]。)

+0

它不起作用 – jenius 2014-10-07 12:46:53

+0

'return(top == 0)&&(top == -1);'总是产生错误; '||'也是错的:一个“黑客”修理。 – 2014-10-07 12:56:29

+0

对不起,我忘了在那里改变它。而且我也有最后一个问题 – jenius 2014-10-07 13:37:51

1

检查顶部被初始化为-1。不要捕获ArrayIndexOutOfBoundsException,找出原因。另外,你的stackIsEmpty应该检查top是否等于-1。