我正在处理需要我使用队列的任务。部分代码直接出自我的书,但是我的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);
}
}
公共T deque方法完全从我的书中复制而来。 的QueueUnderflowException类实际上并没有在我的书所示,所以我在我的接口,并在这个类让其他错误,但我写的代码为
public class QueueUnderflowException extends RuntimeException
{
public QueueUnderflowException()
{
super();
}
public QueueUnderflowException(String message)
{
super(message);
}
}
Netbeans的给我一个错误,它无法找到方法QueueUnderflowException否则如果没有,并且缺少返回语句。
我试图在throws异常行周围添加括号,如下面的代码。这消除了我的“其他没有如果”的错误,我可能可以移动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;
}
}
其实,第三ows子句不是必需的,因为OP声明了QueueUnderflowException来扩展RuntimeException。 – Eran 2014-10-01 04:58:22