Just a simple question, if I created a Queue
class and initialized this
Queue queue = new Queue(5)
In the main method, and then enqueued and dequeued accordingly,
with the following instance variables, and toString()
method:
private int maxSize;
private Planes[] queArray;
private int front;
private int rear;
private int nItems;
public String toString()
{
String result = "[";
for(int i = 0; i <= rear; i++)
{
result += " " + queArray[i];
if(i <= rear - 1)
result += ",";
}
result += " ]";
return result;
}//toString`
What variable do I stop at in the for
loop:
for(int i = 0; i <= rear; i++)
,
Right now I have it at rear
, which doesn't seem to work how I want it to, and I know it's not nItems
, or maxSize
because that will print the entire queue
, including the empty slots, and I just want the updated queue
. I know for a Stack
, you only print up to the top
variable, but I'm more confused for the Queue
class.
These are my enqueue
and dequeue
methods:
public void enqueue(Plane name)
{
if(rear == maxSize-1)
{
rear = -1;
}
rear++;
queArray[rear] = name;
nItems++;
}
public Plane dequeue()
{
Plane temp = queArray[front];
front++;
if(front == maxSize)
{
front = 0;
}
nItems--;
return temp;
}
When you do queue and deque you should manipulate a variable inside the class. So in the beginning it will be equal to 0. After each queue or dequeue accordingly you will ++ or -- it.
Then this is the variable you use in toString to define end boundary for the loop. To use it anywhere in the class like this it should be an instance variable too.
edit: After the code you added, seems like it should be nitems
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.