简体   繁体   English

Queue类的toString()方法

[英]toString() method for Queue class

Just a simple question, if I created a Queue class and initialized this 只是一个简单的问题,如果我创建了一个Queue类并初始化了这个

Queue queue = new Queue(5)

In the main method, and then enqueued and dequeued accordingly, 在main方法中,然后相应地入队和出队,

with the following instance variables, and toString() method: 具有以下实例变量和toString()方法:

 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循环中停在什么变量上:

for(int i = 0; i <= rear; i++) , 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 . 现在,我将它放在rear ,这似乎不符合我的期望,我知道它不是nItemsmaxSize因为它将打印整个queue ,包括空插槽,而我只想更新queue I know for a Stack , you only print up to the top variable, but I'm more confused for the Queue class. 我知道对于Stack ,您只能打印到最top变量,但是对于Queue类我更困惑。

These are my enqueue and dequeue methods: 这些是我的入enqueuedequeue方法:

 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. 因此,在开始时它将等于0。在每个队列或相应的出队之后,您将对其进行++或-。

Then this is the variable you use in toString to define end boundary for the loop. 然后,这就是您在toString中使用的变量,用于定义循环的结束边界。 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 编辑:添加代码后,似乎应该是nitems

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM