我正在尝试创建一个基于数组的出队,但我无法正确获得输出的顺序。现在它是有界的,但是一旦我弄清楚如何正确地使用出队,我可能会使用无界的。
这是我的代码:
public class ArrayBndDequeue<T> implements BoundedDequeueInterface<T>
{
protected final int DEFCAP = 100; // default capacity
protected T[] queue; // array that holds queue elements
protected int numElements = 0; // number of elements n the queue
protected int front = 0; // index of front of queue
protected int rear; // index of rear of queue
public ArrayBndDequeue()
{
queue = (T[]) new Object[DEFCAP];
rear = DEFCAP - 1;
}
public ArrayBndDequeue(int maxSize)
{
queue = (T[]) new Object[maxSize];
rear = maxSize - 1;
}
public void enqueue(T element)
// Throws QueueOverflowException if this queue is full;
// otherwise, adds element to the front of this queue.
{
if (isFull())
throw new DequeueOverflowException("Enqueue attempted on a full queue.");
else
{
front = (front + 1) % queue.length;
queue[front] = element;
numElements = numElements + 1;
}
}
public T dequeue()
// Throws QueueUnderflowException if this queue is empty;
// otherwise, removes rear element from this queue and returns it.
{
if (isEmpty())
throw new DequeueUnderflowException("Dequeue attempted on empty queue.");
else
{
T toReturn = queue[rear];
queue[rear] = null;
rear = (rear + 1) % queue.length;
numElements = numElements - 1;
return toReturn;
}
}
public boolean isEmpty()
// Returns true if this queue is empty; otherwise, returns false
{
return (numElements == 0);
}
public boolean isFull()
// Returns true if this queue is full; otherwise, returns false.
{
return (numElements == queue.length);
}
}
这是我的主要课程:
public class Dequeue
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
String line;
BoundedDequeueInterface<String> queue;
queue = new ArrayBndDequeue<String>(3);
for (int i = 1; i <= 3; i++)
{
System.out.print("Enter a line of text > ");
line = userInput.nextLine();
queue.enqueue(line);
}
System.out.println("\nOrder is:\n");
while (!queue.isEmpty())
{
line = queue.dequeue();
System.out.println(line);
}
}
}
当我运行程序时,我通常会输入:
1
2
3
输出如下:
2
3
1
有什么帮助吗?如果您需要我的代码片段,请告诉我!