gpt4 book ai didi

java - 我怎样才能让这个Java队列display()方法适用于所有数组大小而不仅仅是[5]?

转载 作者:行者123 更新时间:2023-12-01 15:31:34 24 4
gpt4 key购买 nike

 // Queue.java
// demonstrates queue
// to run this program: C>java QueueApp

class Queue
{
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;

public Queue(int s) // constructor
{
maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}

public void insert(long j)
{
if(rear == maxSize-1)
rear = -1;
queArray[++rear] = j;
nItems++;
}


public long remove()
{
long temp = queArray[front++];
if(front == maxSize)
front = 0;
nItems--;
return temp;
}

public long peekFront()
{
return queArray[front];
}

public boolean isEmpty() // true if queue is empty
{
return (nItems==0);
}

public boolean isFull() // true if queue is full
{
return (nItems==maxSize);
}

public int size() // number of items in queue
{
return nItems;
}


public void display()
{ int startFront = front;

for (int j = front ;j <nItems; j++ )
{
System.out.println(queArray[j]);
if (j == nItems-1 )
{ j=0;
System.out.println(queArray[j]);
}


if (j==startFront-1)
return;

}
}
}

class QueueApp
{
public static void main(String[] args)
{
Queue theQueue = new Queue(5); // queue holds 5 items

theQueue.insert(10); // insert 4 items
theQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);

theQueue.remove(); // remove 3 items
theQueue.remove(); // (10, 20, 30)
theQueue.remove();

theQueue.insert(50); // insert 4 more items
theQueue.insert(60); // (wraps around)
theQueue.insert(70);
theQueue.insert(80);


theQueue.display();


while( !theQueue.isEmpty() ) // remove and display
{ // all items
long n = theQueue.remove(); // (40, 50, 60, 70, 80)
System.out.print(n);
System.out.print(" ");
}
System.out.println("");

} // end main()
} // end class QueueApp

好的,这是书本之外的基本队列代码。我正在尝试创建一个显示方法,该方法将按从前到后的顺序显示队列。 (这是一项作业,我知道这不切实际......)如果我按原样运行程序,它将按从前到后的顺序显示队列(至少我相信我是这样做的)。我遇到的问题是,如果我更改 nItems,它就会停止工作。例如,如果添加代码行 theQueue.remove();在对显示的调用的正上方,该方法停止工作,我知道这是因为前面现在= 4,而不是3,并且它不会进入需要前面为< nItems, 4<的for方法4 不正确,因此 for 循环不会启动。

最佳答案

只需使用类似的东西:

public void display() {
for (int i = 0; i < nItems; i++) {
System.out.println(queArray[(front + i) % maxSize]);
}
}

关于java - 我怎样才能让这个Java队列display()方法适用于所有数组大小而不仅仅是[5]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472943/

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