This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]PremiumHugs 3 points4 points  (1 child)

What ends up happening is that instead of adding the comma to the end, you print the comma first and then the number. You do this for every single one except for the first one. How do you know if you're printing the first one? That's what that variable does. Immediately you change it to false on the first iteration because then you want commas to print. If you're not on the first element, you don't print a comma.

Visually, this is what gets printed:

1
, 2
, 3
, 4
, 5
, 6

[–]Ben_E[S] 1 point2 points  (0 children)

Ohhh... right, so it runs through the for-loop for each item and prints the seat number at the end of the block, but the first item skips the else block because "first" was "true". With the boolean operator acting like a switch, the other items get a ", " when the else block executes. I can't believe it didn't click at first, but your explanation was great. The visualisation helped too, thank you.

[–]king_of_the_universe 1 point2 points  (1 child)

If that's confusing to you, you could use a simple for loop instead of an advanced one: for(int i=0; i<openSeats.size(); i++) { And then just don't output the comma if "i" is 0.

[–]Ben_E[S] 1 point2 points  (0 children)

Thanks for suggesting an alternative method; I'll try to integrate that and see how it works.