【发布时间】:2021-08-23 21:17:51
【问题描述】:
这是我实现Queue 的代码。运行代码时出现问题,在peek()方法中显示运行时错误。
public class Queue {
int size;
int frontIndex;
int backIndex;
int arr[];
Queue()
{
size = 5;
frontIndex =-1;
backIndex = -1;
arr = new int[size];
}
public int peek() {
return arr[frontIndex];
}
public void enqueue(int data)
{
if(isFull())
{
System.out.println("Queue is overflow");
}
else
{
System.out.println("Insert " + data);
backIndex ++;
arr[backIndex]=data;
}
}
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(15);
queue.enqueue(18);
System.out.println("Front element of queue is " + queue.peek());
}
}
这是我得到的错误:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5 "
【问题讨论】:
-
当您将队列中的项目排入队列但在
peek方法中时,您递增backIndex,您正在访问为-1 的frontIndex,因此出现越界异常。您忘记在enqueue方法中更新frontIndex。 -
您用 -1 和
peek初始化frontIndex尝试访问该索引上的数组。所以,完全在意料之中。为什么你 不期待这个? -
@Fildor 是的,你是对的,我明白我在哪里犯了错误。感谢支持。
-
欢迎来到 SO。请缩进你的代码。适当的缩进不是可选的,但对可读性至关重要。当您在 SO 上发帖时,请让人们尽可能轻松地帮助您。谢谢!