【问题标题】:Queue implementation, peek() method error队列实现,peek() 方法错误
【发布时间】: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 上发帖时,请让人们尽可能轻松地帮助您。谢谢!

标签: java package


【解决方案1】:

您永远不会更新您的frontIndex

你可以做的是:

frontIndex 设置为0 而不是-1,这样peek() 在您从队列中取出第一个元素之前不会抛出异常。我猜想用 -1 初始化它的原因是,你会在从队列中获取元素之前递增。当您在访问队列的第一个元素之前尝试将peek() 加入队列时,这是有问题的。

解决方法是简单地将 frontIndex 初始化为 0,然后您从队列中获得一个值之后将其递增。

如果peek() 应该实际将值从队列中取出,只需在peek 方法中增加frontIndex

public int peek() {
    frontIndex++;
    return arr[frontIndex];
}

【讨论】:

    猜你喜欢
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2016-07-02
    相关资源
    最近更新 更多