gpt4 book ai didi

java - 为什么我收到错误“找不到方法”?

转载 作者:行者123 更新时间:2023-11-30 03:44:17 25 4
gpt4 key购买 nike

我正在做一项需要使用队列的作业。部分代码直接来 self 的书,但是我在 ArrayUnbndQueue 类的出列方法中遇到了几个错误。

public class ArrayUnbndQueue<T> implements UnboundedQueueInterface<T>
{
protected final int DEFCAP = 100; // default capacity
protected T[] queue; // array that holds queue elements
protected int origCap; // original capacity
protected int numElements = 0; // number of elements in the queue
protected int front = 0; // index of front of queue
protected int rear = -1; // index of rear of queue

public ArrayUnbndQueue()
{
queue = (T[]) new Object [DEFCAP];
rear = DEFCAP - 1;
origCap = DEFCAP;
}

public ArrayUnbndQueue(int origCap)
{
queue = (T[]) new Object[origCap];
rear = origCap - 1;
this.origCap = origCap;
}

private void enlarge()
{
T[] larger = (T[]) new Object[queue.length + origCap];

int currSmaller = front;
for (int currLarger = 0; currLarger < numElements; currLarger++)
{
larger[currLarger] = queue[currSmaller];
currSmaller = (currSmaller + 1) % queue.length;
}

// update instance variables
queue = larger;
front = 0;
rear = numElements - 1;
}

public void enqueue(T element)
{
if (numElements == queue.length)
enlarge();
rear = (rear + 1) % queue.length;
queue[rear] = element;
numElements = numElements + 1;
}

public T dequeue()
{
if (isEmpty())
throws new QueueUnderflowException("Dequeue attempted on empty queue.");
else
{
T toReturn = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
numElements = numElements -1;
return toReturn;
}
}

public boolean isEmpty()
{
return (numElements == 0);
}

}

公共(public) T deque 方法完全是从我的书中复制的。QueueUnderflowException 类实际上并未在我的书中显示,因此我在接口(interface)和此类中遇到了其他错误,但我为此编写了代码

public class QueueUnderflowException extends RuntimeException
{
public QueueUnderflowException()
{
super();
}
public QueueUnderflowException(String message)
{
super(message);
}
}

Netbeans 给我一个错误,它无法找到方法 QueueUnderflowException,否则没有 if,并且缺少 return 语句。

我尝试在抛出异常行周围添加括号,如下面的代码。这消除了我的“else with no if”错误,并且我可能可以将 return 语句移至 else 语句的外部,但我仍然收到找不到方法错误

public T dequeue()
{
if (isEmpty())
{
throws new QueueUnderflowException("Dequeue attempted on empty queue.");
}
else
{
T toReturn = queue[front];
queue[front] = null;
front = (front + 1) % queue.length;
numElements = numElements -1;
return toReturn;
}
}

最佳答案

抛出 new QueueUnderflowException("尝试在空队列上出队。");

应该是

抛出 new QueueUnderflowException("尝试在空队列上出列。");

关于java - 为什么我收到错误“找不到方法”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com