HelpNeeder
HelpNeeder

Reputation: 6490

How else to rewind queue?

I build this code which displays all entries of an array in queue fashion. The problem is that I was told that this could be done without for statement which rewind content of i to 0, but I can't figure out how.

How else this could be done?

   public void display()
   {
       int i = frontIndex;

       while(true)
       {
           if (i == numberOfItems)
               i = 0;

           System.out.print(array[i++] + " ");

           if (i == rearIndex + 1)
               break;
       }
   }

Upvotes: 1

Views: 147

Answers (3)

artaxerxe
artaxerxe

Reputation: 6421

I think you should use a LinkedList under Queue interface. For understanding me better, look at LinkedList and Queue javadocs.

Upvotes: 0

amit
amit

Reputation: 178521

You can use the % operator and print the i % numberOfItems:

It is not tested, but it should be something along the lines of:

for (int i = frontIndex; i % numberOfItems != rearIndex+1; i++) { 
   System.out.print(array[(i++) % numberOfItems)] + " ");
}

The idea is (array.length + k) % array.length == k, so using the % operator, is actually equivalent to resetting the index i back to 0.

Upvotes: 5

Jan Hruby
Jan Hruby

Reputation: 1497

I would use Arrays.toString() method instead of your code if you are just displaying content of array

Upvotes: 0

Related Questions