Other 2010 FR Questions FR other years Be Prepared Home
A-1
Part (a)
  public int getTotalBoxes()
  {
    int total = 0;
    for (CookieOrder o : orders)
      total += o.getNumBoxes();
    return total;
  }

Part (b)
  public int removeVariety(String cookieVar)
  {
    int total = 0;
    for (int i = orders.size() - 1; i >= 0; i--) 1
    {
      CookieOrder o = orders.get(i);
      if (o.getVariety().equals(cookieVar)) 2
      {
        total += o.getNumBoxes();
        orders.remove(i);
      }
    }
    return total;
  } 3, 4
Notes:
  1. The list is traversed in the reverse order, so that the removed elements do not affect the indices of the remaining elements.

  2. equals, not ==.

  3. Alternative solution with a while loop, traversing the list from the beginning:
      public int removeVariety(String cookieVar)
      {
        int total = 0;
        int i = 0;
        while (i < orders.size())
        {
          CookieOrder o = orders.get(i);
          if (o.getVariety().equals(cookieVar))
          {
            total += o.getNumBoxes();
            orders.remove(i);
          }
          else
            i++;
        }
        return total;
      }
  4. Alternative solution with an iterator (not in the AP subset):
      public int removeVariety(String cookieVar)
      {
        int total = 0;
        Iterator iter = orders.iterator();
    
        while (iter.hasNext())
        {
          CookieOrder o = iter.next();
          if (o.getVariety().equals(cookieVar))
          {
            total += o.getNumBoxes();
            iter.remove();
          }
        }
        return total;
      }

Other 2010 FR Questions | Back to Contents

Copyright © 2010 by Skylight Publishing
support@skylit.com