队列toString但没有正确的顺序JAVA

时间:2014-10-27 17:01:26

标签: java queue tostring joptionpane

我需要将我的队列转换为字符串,以便我可以在JOptionPane对话框中显示,但是当我转换时,数字不按顺序排列。我知道问题出在我的toString()方法中,但我不确定如何修复它或者正确的方式来说明正确的顺序转换为字符串。有什么建议吗?

public interface Queue<T>
{
    public void add(T element);
    public T remove();
    public T element();
    public boolean isEmpty();
    public int size();
}


  public class ArrayQueue<T> implements Queue<T>
    {
      private final int INITIAL_SIZE=10;
      // private T[] buffer;
      private int front, rear, count;


  public ArrayQueue()
  {
    front =0;
    rear=0;
    count=0;
  }
   T[]  buffer = (T[]) new Object[INITIAL_SIZE];

    public void add(T element)
    {
      if(count==buffer.length)
        addStorageSpace();
      buffer[rear] = element;
      rear = (rear+1)%buffer.length;
      count++;
    }
    public T remove()
    {
      T element = buffer[front];
      front = (front +1)%buffer.length;
      count--;
      return element;
    }
    public T element()
    {
      return buffer[front];
    }
    public boolean isEmpty()
    {
      return (count ==0);
    }
    public int size()
    {
      return count;
  }
    public String toString()
    {
      String output ="";
      for(int i=0;i<20;i++)
        output +=(buffer[i])+" ";
      return output;
    }
    private void addStorageSpace()
    {
      T[] tmp = (T[]) new Object[2*buffer.length];
      for(int i=0; i<count; i++)
        tmp[i] = buffer[(front+i)%buffer.length];
      front =0;
      rear= count;
      buffer = tmp;
    }
}






import java.util.Random;
import javax.swing.JOptionPane;
public class Oct22
{

  public static void main(String[] arg)
  {
    int x;
    int size;
    Random rnd =  new Random();
    Queue<Integer> queue = new ArrayQueue<Integer>();
    Queue<Integer> queue2 = new ArrayQueue<Integer>();
    //for(char c='a'; c<= 'z'; c++)
   //   queue.add(c);

    for(int i=0;i<20;i++)
      queue2.add(rnd.nextInt(100));


    size = queue2.size();
    for(int i=0;i<size;i++)
    {
     x=queue2.remove();
    if(x%3==0)
      queue.add(x);
    else
      queue2.add(x);
    }

    size = queue2.size();
    for(int i=0;i<size;i++)
    {
     x=queue2.remove();
    if(x%3==1)
      queue.add(x);
    else
      queue2.add(x);
    }
     size = queue2.size();
    for(int i=0;i<size;i++)
    {
     x=queue2.remove();
    if(x%3==2)
      queue.add(x);   
    } 



    System.out.println(queue.size())
      ;
    System.out.println(queue2.size());

    System.out.println("the size of queue is: " + queue.size());  
    while(!queue.isEmpty())
      System.out.print(queue.remove()+ " ");
    System.out.println("\n---------------------------------");
    while(!queue2.isEmpty())
     System.out.print(queue2.remove()+" ");
    JOptionPane.showMessageDialog(null, queue2.toString() +" ");


    }
}`

0 个答案:

没有答案