[英]Error java.lang.ArrayIndexOutOfBoundsException: -1 on my code
This is my code. 这是我的代码。 There is an error showing on the terminal window. 终端窗口上显示错误。 It says java.lang.ArrayIndexOutOfBoundsException: -1 at top--; 它说java.lang.ArrayIndexOutOfBoundsException:-1在顶部-; and while (!stack.isEmpty()). 并同时(!stack.isEmpty())。 Please help me solve this issue. 请帮我解决这个问题。 I looked it up online but it did not help much. 我在网上查询了一下,但没有太大帮助。 That is why I am asking you for help. 这就是为什么我要你寻求帮助。
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());
}
}
}
}
Your isEmpty() and pop() functions do not work together. 您的isEmpty()和pop()函数不能一起使用。 Think about this: when you decrement top and set the index to null does the actual size of the list get adjusted? 考虑一下:当减小top并将索引设置为null时,列表的实际大小是否得到调整? The fix will come by changing isEmpty() I am just using pop() as an example. 该解决方案将通过更改isEmpty()来实现,我仅以pop()为例。
Your isEmpty()
method is implemented incorrectly. 您的isEmpty()
方法实现不正确。
public boolean isEmpty()
{
return stack.length == 0;
}
It is currently comparing the size or capacity of of the stack
array. 当前正在比较stack
阵列的大小或容量。 This is a constant, it does not change. 这是一个常数,不会改变。 The value of 的价值
stack.length
is always equal to the value you used to initialize the array 始终等于您用来初始化数组的值
new Object[length];
You should be comparing to the number of elements in your stack. 您应该将其与堆栈中的元素数量进行比较。
public boolean isEmpty()
{
return top == 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.