嘿,我有一個問題,爲什麼我的程序拋出一個ArrayIndextOutofBounds異常 我在互聯網上到處尋找,並通過代碼,但我知道我失去了一些東西。 這是一個已經實現的堆棧,並坦率地說,我不是這是我在做什麼恰好是100%我的第一個程序。初學者堆棧,OutofBoundsException異常Java
我認爲問題來自我的isEmpty方法,但不能完全看到我在做什麼錯誤..必須有一個更簡單的方法來測試堆棧是否爲空或不是? 任何幫助將不勝感激。
PS:我是正確設置我的測試堆棧?
繼承人我的代碼:
import java.util.Arrays;
public class ArrayStack<T> implements StackADT<T> { private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
private int emptyCount = 0;
//Creates an empty stack using the default capacity.
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
//Creates an empty stack using the specified capacity.
@SuppressWarnings("unchecked")
public ArrayStack(int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
/* Adds the specified element to the top of this stack, expanding
the capacity of the array if necessary.*/
public void push(T element)
{
if (size() == stack.length)
expandCapacity();
stack[top] = element;
top++;
}
/*Creates a new array to store the contents of this stack with
twice the capacity of the old one.*/
private void expandCapacity()
{
stack = Arrays.copyOf(stack, stack.length * 2);
}
/*Removes the element at the top of this stack and returns a
reference to it.*/
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top] = null;
return result;
}
/*Returns a reference to the element at the top of this stack.
The element is not removed from the stack.*/
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top-1];
}
//Returns true if this stack is empty and false otherwise.
public boolean isEmpty()
{
for(int i = 0; i < stack.length; i++)
{
if (stack[i] == null)
emptyCount++;
}
if(emptyCount != stack.length-1)
return false;
else
return true;
}
//Returns the number of elements in this stack.
public int size()
{
return stack.length;
}
//Returns a string representation of this stack.
public String toString()
{
String output = "The element at the top of the stack is: " + peek() + "\n" +
"It is " + isEmpty() + " that the stack is empty." + "\n" +
"The number of elements in the stack is: " + size();
return output;
}
}
而且我的司機/ test文件:
public class StackTest
{
public static void main(String[] args) throws EmptyCollectionException
{
ArrayStack stack = new ArrayStack(5);
System.out.println(stack);
}
}
非常感謝了幫助,程序現在運行良好! – OGLOKE
isEmpty()函數正常,效率不高,但仍然有效... 問題出在peek()函數中 – Tal87
peck()函數沒有問題。我測試過了,它工作正常 – luizcarlosfx