In the for loop in the Java code below, the head person is removed from peopleInQueue, and it outputs his/her name and that he/she have purchased a ticket, then it outputs your position in the queue. When you are at the head position, it outputs that you can purchase your ticket and the looping is over.
The problem is if the input is of 7 items, for example:
Bruce Banner
Steve Rogers
Tony Stark
Natalia Romanova
Peter Parker
You
-1
Then the actual output is the one below. However, it exits sooner than expected. Not even reaching Peter Parker or even the objective that is You.
Welcome to the ticketing service...
You are number 6 in the queue.
Bruce Banner has purchased a ticket.
You are now number 5
Steve Rogers has purchased a ticket.
You are now number 4
Tony Stark has purchased a ticket.
You are now number 3
Natalia Romanova has purchased a ticket.
You are now number 2
The expected output should be like this:
Welcome to the ticketing service...
You are number 6 in the queue.
Bruce Banner has purchased a ticket.
You are now number 5
Steve Rogers has purchased a ticket.
You are now number 4
Tony Stark has purchased a ticket.
You are now number 3
Natalia Romanova has purchased a ticket.
You are now number 2
Peter Parker has purchased a ticket.
You are now number 1
You can now purchase your ticket!
Here is the code:
import java.util.LinkedList;
import java.util.Queue;
class Main {
public static void main (String[] args) {
Queue<String> peopleInQueue = new LinkedList<>();
peopleInQueue.add("Bruce Banner");
peopleInQueue.add("Steve Rogers");
peopleInQueue.add("Tony Stark");
peopleInQueue.add("Natalia Romanova");
peopleInQueue.add("Peter Parker");
peopleInQueue.add("You");
peopleInQueue.add("-1");
int youPosition = 6;
System.out.println("Welcome to the ticketing service... ");
System.out.println("You are number " + youPosition + " in the queue.");
for(int i=0;i<peopleInQueue.size();i++){
String name = peopleInQueue.peek();
if(name.equals("You")){
System.out.println("You can now purchase your ticket!");
break;
}
else{
youPosition--;
peopleInQueue.poll();
System.out.println(name+ "has purchased a ticket.");
System.out.println("You are now number "+ youPosition);
}
}
}
}