这是我的代码。终端窗口上显示错误。它说java.lang.ArrayIndexOutOfBoundsException:-1在top--;和while(!stack.isEmpty())。请帮我解决这个问题。我在网上查了一下,但没什么用。这就是我向你寻求帮助的原因。
import java.util.*;
public class ArrayStack<T> implements StackADT<T>
{
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack(int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
public void push(T element)
{
if (size() == stack.length)
expandCapacity();
stack[top] = element;
top++;
}
private void expandCapacity()
{
stack = Arrays.copyOf(stack, stack.length * 2);
}
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top] = null;
return result;
}
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top-1];
}
public boolean isEmpty()
{
return stack.length == 0;
}
public int size()
{
return top;
}
public static void main(String[] args)
{
ArrayStack<Character> stack = new ArrayStack<Character>();
String sentence = " ", word;
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
sentence= in.nextLine();
System.out.println("Reversing each word:");
Scanner sentenceScanner = new Scanner(sentence);
while(sentenceScanner.hasNext())
{
word = sentenceScanner.next();
for(int i= 0; i<word.length(); i++)
{
stack.push(word.charAt(i));
}
while (!stack.isEmpty())
{
System.out.print(stack.pop());
}
}
}
}
答案 0 :(得分:0)
您的isEmpty()和pop()函数无法一起使用。想一想:当你减去top并将索引设置为null时,列表的实际大小是否会被调整?修复将通过更改isEmpty()我只是使用pop()作为示例。
答案 1 :(得分:0)
您的isEmpty()
方法实施不正确。
public boolean isEmpty()
{
return stack.length == 0;
}
目前正在比较stack
数组的大小或容量。这是一个常数,它不会改变。
stack.length
始终等于用于初始化数组的值
new Object[length];
您应该与堆栈中的元素数量进行比较。
public boolean isEmpty()
{
return top == 0;
}