Other 2004 FR Questions FR other years Be Prepared Home
A-1
Part (a)
  // postcondition: returns the number of words in this WordList that
  //                are exactly len letters long
  public int numWordsOfLength(int len)
  {
    int count = 0;

    for (int i = 0; i < myList.size(); i++)
      if (((String)myList.get(i)).length() == len) 1
        count++;

    return count;
  }
Notes:
  1. The cast to String is necessary to call its length method.

Part (b)
  // postcondition: all words that are exactly len letters long
  //                have been removed from this WordList, with the
  //                order of the remaining words unchanged
  public void removeWordsOfLength(int len)
  {
    int i = 0;

    while (i < myList.size()) 1
    {
      if (((String)myList.get(i)).length() == len)
        myList.remove(i); 2
      else
        i++;
    }
  } 3
Notes:
  1. A while loop is more convenient for a traversal with removals than a for loop.

  2. When we remove a value, myList.size() is decremented and the indices of the subsequent values are decremented by one.  In that case, we don't increment i.

  3. A solution with an iterator is acceptable, too, and it is actually shorter and safer:
      public void removeWordsOfLength(int len)
      {
        Iterator iter = myList.iterator();
    
        while (iter.hasNext())
        {
          if (((String)iter.next()).length() == len)
            iter.remove();
        }
      }

Other 2004 FR Questions | Back to Contents

Copyright © 2004 by Skylight Publishing
support@skylit.com