2015-02-12 6 views
-1

Я пытаюсь запустить этот код, чтобы узнать Java, но я обнаружил ошибку во время выполнения:ArrayOutOfBoundException ошибка во время выполнения

import java.util.*; 

public class ArrayStack<E> implements StackInterface<E>{ 
    private E[] theStack; 
    private int capacity; 
    public static final int CAPACITY = 1000; 
    private int top = -1; 

    public ArrayStack() { 
     top = -1;  // empty stack 
     theStack = (E[])(new Object[10]); // make room for at least 10 items 
    } 

    public ArrayStack(int initialCapacity) throws IllegalArgumentException { 
    /*The constructor creates a new stack with the specified capacity, and throws an IllegalArgumentException 
    if the specified capacity is less than zero.*/ 
     if (initialCapacity < 1) 
      throw new IllegalArgumentException 
        ("initialCapacity must be >= 1"); 
     theStack = (E[]) new Object [capacity]; 
     capacity = initialCapacity; 
     top = -1; 

    } 

    public void push(E element) throws NullPointerException,IllegalStateException { 
     if (size() == capacity) 
      throw new IllegalStateException("Stack is full."); 
     if (element == null) { 
      throw new NullPointerException("Can't push a null element"); 
     } 

     if (theStack.length == top + 1) { 
      theStack = java.util.Arrays.copyOf(theStack, theStack.length * 2); 
     } // else, there already is room for one new element 
     top++; 
     theStack[top] = element; 
    } 
    public int size() { return top+1; } 
    public boolean isEmpty() { 
     return (top < 0); 
    } 
    public E pop() throws EmptyStackException{ 
     E element; 
     if(isEmpty()) { 
      throw new EmptyStackException(); 
     } 

     element = theStack[top]; 
     theStack[--top] = null; 
     return element; 
    } 

    public int depth() { 
     return size(); 
    } 

    public int capacity() { 
     return capacity; 
    } 

    public void flip() { 
     reverse(theStack, 0, size() -1); 
    } 

    public void reverse(E[] x, int i, int j){ 
     if(i<j){ 
      E tmp = x[i]; 
      x[i] = x[j]; 
      x[j] = tmp; 
      reverse(x, ++i, --j); 
     } 
    } 

    public void transferTop(ArrayStack<E> s) throws EmptyStackException { 
    /*The transferTop method transfers the element from the top of stack s to the top of the current stack (this).*/ 
     if(isEmpty()) { 
      throw new EmptyStackException(); 
     } 
     E x; 
     x = s.pop(); 
     this.push(x); 

    } 

    public E replaceTop(E element) throws NullPointerException { 
    /*The replaceTop method replaces the top element of the stack with the specified element and returns the original top element.*/ 
     if(element == null) throw new NullPointerException("Can't push a null element"); 
     theStack[top] = element; 
     return theStack[top]; 
    } 

    public String toString() { 
     String s; 
     s = "["; 
     if (size() > 0) 
      s += theStack[0]; 
     if (size() > 1) 
      for (int i = 1; i <= size() - 1; i++) { 
       s += ", " + theStack[i]; 
      } 
     return s + "]"; 
    } 

    public void status(String op, Object element) { 
     System.out.print("------> " + op); // print this operation 
     System.out.println(", returns " + element); // what was returned 
     System.out.print("result: size = " + size() + ", isEmpty = " 
       + isEmpty()); 
     System.out.println(", stack: " + this); // contents of the stack 
    } 

    @SuppressWarnings("unchecked") 
    public static void main(String[] args) { 
     Object o; 
     //ArrayStack(int initialCapacity) 
     StackInterface<Integer> A = new ArrayStack<Integer>(100); 
     A.status("new ArrayStack<Integer> A", null); 

     A.push(7); 
     A.status("A.push(7)", null); 
     o = A.pop(); 
     A.status("A.pop()", o); 
     A.push(9); 
     A.status("A.push(9)", null); 
     o = A.pop(); 
     A.status("A.pop()", o); 
     ArrayStack<String> B = new ArrayStack<String>(); 
     B.status("new ArrayStack<String> B", null); 
     B.push("Bob"); 
     B.status("B.push(\"Bob\")", null); 
     B.push("Alice"); 
     B.status("B.push(\"Alice\")", null); 
     o = B.pop(); 
     B.status("B.pop()", o); 
     B.push("Eve"); 
     B.status("B.push(\"Eve\")", null); 
    } 
} 

A.push (7) операция сгенерировал ArrayIndexOutOfBoundsException. Мне было интересно, что нужно изменить в моем методе push(). Заранее спасибо.

+0

Можете ли вы опубликовать трассировку стека? –

+0

'------> новый ArrayStack A, возвращает null' ' result: size = 0, isEmpty = true, stack: [] ' ' Исключение в потоке "main" java.lang.ArrayIndexOutOfBoundsException: 0' '\t на ArrayStack.push (ArrayStack.java:61)' ' \t на ArrayStack.main (ArrayStack.java:172)' '' '' линия 61: это «theStack [наверх] = элемент; " строка Строка 172: «A.push (7);» Линия – user1685717

+0

'------> новый ArrayStack А, возвращается null' ' Результат: размер = 0, IsEmpty = TRUE, стек: [] '' Исключение в потоке "основного" java.lang.ArrayIndexOutOfBoundsException : 0' '\t на ArrayStack.push (ArrayStack.java:61)' ' \t в ArrayStack.main (ArrayStack.java:172)' '' '' Строка 61: это «theStack [top] = элемент; " строка Строка 172: «A.push (7);» Линия – user1685717

ответ

1
theStack = (E[]) new Object [capacity]; 
capacity = initialCapacity; 

Вы выделяете массив нулевого размера, потому что вы используете capacity когда он установлен в 0, а умолчанию используется именно не правильное значение.

+0

это было. Я изменил порядок кода, и он сработал! благодаря – user1685717

Смежные вопросы