I’m working a quiz game and i added a category(enum) to every question and now i wanted to let the player decide which category he wants to play.
i tried:
for (int i = 0; i < unansweredFacts.Length; i++)
{
if ((int)unanswerdFacts*.category != setCategory)*
{
unansweredFacts.removeAt(i);
}
}
but this code doesn’t work
In a list, when you delete an item at a position, all the following items move down one index so there’s no empty space. So when you have this:
[ a, b, c, d, e ]
and remove at [2], you get
[ a, b, d, e ]
Which means that i, your counter, is pointing on “d” after the deletion. Then, the loop continues with i++
, moving it to “e”. The result: “d” isn’t even checked.
The solution:
for (int i = 0; i < unansweredFacts.Length; i++)
{
if ((int)unanswerdFacts*.category != setCategory)*
{
unansweredFacts.removeAt(i);
i–;
}
}
or, if you like this more (it’s a question of taste):
for (int i = 0; i < unansweredFacts.Length;) // no i++ here
{
if ((int)unanswerdFacts*.category != setCategory)*
{
unansweredFacts.removeAt(i);
}
else
{
i++;
}
}