Вопрос

Hey I have a question as to why my program is throwing an ArrayIndextOutofBounds Exception I've looked everywhere on the internet and have gone through the code but I know I'm missing something. This is my first program that has implemented stacks and to be quite frank I'm not exactly 100% on what it is I am doing.

I think the problem is coming from my isEmpty method but can't exactly see what I am doing wrong.. there must be an easier way to test if a stack is empty or not? Any help would be greatly appreciated.

PS: am I setting up my test stack correctly?

Heres my code:

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;
}
}

And my driver/test file:

public class StackTest
{
    public static void main(String[] args) throws EmptyCollectionException
    {
        ArrayStack stack = new ArrayStack(5);
        System.out.println(stack);
    }
}
Это было полезно?

Решение 3

the problem is in your isEmpty() method. Try do something like this

public boolean isEmpty()
{
    for (T element : stack)
    {
        if(element != null)
        {
            return false;
        }
    }

    return true;
}

another problem is your size function, it always returns the length of the array.

try do something like this:

public int size()
{
    int count = 0;
    for (T element : stack)
    {
        if(element != null)
            count++;
    }

    return count;
}

Другие советы

Your problem is the isEmpty() method. The stack is empty when top==0 and has nothing to do with the contents of the stack elements.

i guess the problem is in the peek() function and not in isEmpty() in peek() you use stack[top - 1] which means stack[-1] another problem though is the size() function... it doesn't return the number of elements in the stack but the length of the stack.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top