SJSU/Udacity CS046

Lesson 8 - More About Classes

  1. Quiz: Discovering Classes
  2. Naming Classes Well
  3. Quiz: Photography Company
  4. Thinking About the Names
  5. Quiz: Discovering Instance Variables
  6. Quiz: Counting
  7. Quiz: Collecting
  8. Quiz: Homework Scores Without Collecting
  9. Quiz: Properties
  10. Quiz: Static Methods
  11. Creating a Static Method
  12. Quiz: Some Methods that Should Have Been Static
  13. Quiz: Static Variables
  14. Quiz: IDs the Quick and Dirty Way
  15. IDs the Better Way
  16. Quiz: Implement tryToAdd
  17. Quiz: Drive
  18. Quiz: Implement loadPassengers
  19. Quiz: driveCars
  20. Quiz: Running the Car Simulation
  21. Quiz: Optional Challenge: Implementing the Photography Story
  22. Quiz: Coupling Between Classes
  23. Quiz: Don't Print in addPassenger
  24. Quiz: Don't Print in Drive
  25. Quiz: Coupling in the Photography Example
  26. Packages
  27. Quiz: Reorganizing the Carshare Classes

Quiz: driveCars

The answer in the video is wrong. See if you can spot the error.

The problem is that there are two i++: in the for loop and in the else.

It is always dangerous to change the variable that is controlled by the for loop. A while loop is the safer choice:

            int i = 0;
            while (i < cars.size())
            {
                Car c = cars.get(i);
                c.drive();
                if (c.hasArrived())
                {
                    cars.remove(i);
                }
                else
                {
                    i++;
                }
            }

Alternatively, if you use a for loop and remove elements, traverse the list backwards:

            for (int i = cars.size() - 1; i >= 0; i--)
            {
                Car c = cars.get(i);
                c.drive();
                if (c.hasArrived())
                {
                    cars.remove(i);
                }
            }

Problem on this page?

Your name:

Your email address:

Problem description:

To protect against spam robots, please answer this simple math problem:
× =