The MasterOrder problem from the 2010 AP Computer Science Exam is typical of free response problems that test lists. The problem requires you to manipulate a List and the objects inside.

MasterOrder is #1 from the 2010 AP Computer Science Free Response.

Part (a) getTotalBoxes method

public int getTotalBoxes()
    int boxes = 0;

    for (CookieOrder order : orders)
        boxes += order.getNumBoxes();

    return boxes;

On the free response, when in doubt, use a regular loop (for or while). See Enhanced for loop exercises for information on when enhanced for loops are appropriate, and to practice with them.

Part (b) removeVariety method

public int removeVariety(String cookieVar)
    int boxesRemoved = 0;

    for (int i = orders.size() - 1; i >= 0; i--)
        if (cookieVar.equals(orders.get(i).getVariety()))
            boxesRemoved += orders.remove(i).getNumBoxes();

    return boxesRemoved;

See ArrayList practice for details on adding to and removing from an ArrayList within a loop.

2010 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on MasterOrder