Final answer:
The displayQueue method iterates from the front to the rear of the queue and handles wrapping around the array, ensuring a correct display of all items in the proper order. It uses the modulus operator for seamless traversal and correctly manages empty or single-item queues.
Step-by-step explanation:
To add a method to the Queue class that displays the contents of the queue from the first item inserted to the last, regardless of whether the sequence is broken by wrapping around the end of the array, you can implement a new method named displayQueue. This method will manage the potential wraparound by iterating from the front to the rear index, taking into consideration the maximum size of the queue (maxSize). It will correctly handle the display for the cases where the queue is empty or contains one item.
Here is the displayQueue method you should add to the Queue class:
public void displayQueue() {
if(isEmpty()) {
System.out.println("Queue is empty");
} else {
System.out.print("Queue from front to rear: ");
int index = front;
for(int i = 0; i < nItems; i++) {
System.out.print(queArray[index] + " ");
index = (index + 1) % maxSize;
}
System.out.println();
}
}
The displayQueue method checks if the queue is empty before proceeding to print its contents. If not, it starts from the front index and prints elements in order until it reaches the rear, wrapping around the array by using the modulus operator.