See, I've run into the same rock twice. There is a collection with things in it, and I have to do something with the first thing that appears of that collection that meets certain condition, then stop it right there.
I just don't know how to do that.
Today I had an OOP exam, we use Java. I had to iterate through an ArrayList of airstrips to see if they were empty. If I find an empty airstrip, then I assign to it a plane that is waiting to land. I just didn't knew how to do that.
First I tried a for with an iterator (the code did more stuff but the essential is this) :
for (AirstripClass airstrip : airstripArray)
{
if (airstrip.getPlane == null)
airstrip.addPlane(plane);
else
System.out.println("There are no empty airstrips");
}
That didn't worked. It ended up assigning the same plane to all the empty airstrips. Then I tried a common for loop with an extra boolean condition:
int i;
boolean foundEmptyStrip = false;
for (int i = 0; i < airstripArray.size(); foundEmptyStrip != true; i++ )
{
if (airstripArray.getPlane == null)
{
airstripArray.addPlane(plane);
foundEmptyStrip = true;
}
else
System.out.println("There are no empty airstrips");
}
Couldn't get that one working either. Wait... I'm so stupid, I've should initialized the boolean inside the for right? Anyway it wouldn't have worked, it would print "There are no empty airstrips" each time it finds a filled airstrip (which could happen several times until it finds an empty airstrip in the array).
I had a similar issue in a final a month ago. In that course we used Ada (similar to Pascal). I had to traverse a character array for a specific character, replace it, and then stop it right there. Made a for loop (in Ada you can't use several conditions on the same for loop as far as I know) and used an exit in the middle. It worked fine but the teacher said it was wrong using an exit because it doesn't fits in the paradigm (pretty much like a goto).
Gah! I just can't code in such time restraints like the ones we have in exams. If you say to me "Have it ready for next week", there is no problem, even if I end up actually coding it in a few hours, now if you tell me "Have it ready in three hours, by 8pm" then I couldn't code to save my life.