好的,因此此程序需要使用队列分隔整数流。我得到一个输出,但它的输出顺序不理想,首先是整数可被3整除,然后是1%3,然后是2%3
有什么建议么?
这是我的代码:

  import java.util.Random;

  public class Oct22
{

    public static void main(String[] arg)
   {
          int x;
       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));


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

for(int i=0;i<queue2.size();i++)
{
 x=queue2.remove();
if(x%3==1)
  queue.add(x);
else
  queue2.add(x);
}
 for(int i=0;i<queue2.size();i++)
{
 x=queue2.remove();
if(x%3==2)
  queue.add(x);
else
  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()+" ");

}


}

最佳答案

在每个循环中,更改以下内容:

for(int i=0;i<queue2.size();i++)


对此:

int size = queue2.size();
for(int i=0;i<size;i++)


这是必要的,因为在删除和添加项目时,queue2的大小在循环内不断变化。

顺便说一句,最后一个循环可以替换为

queue.addAll(queue2);


因为在这一点上,queue2中所有剩余的数字都应该有2的余数。

完整代码:

      int x;
      int size;
      Random rnd =  new Random();
      Queue<Integer> queue = new ArrayDeque<Integer>();
      Queue<Integer> queue2 = new ArrayDeque<Integer>();

      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);
        else
          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()+" ");

关于java - 如何使用队列对整数流进行排序?实验室JAVA,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26581543/

10-14 19:27
查看更多