Other 2004 FR Questions FR other years Be Prepared Home
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

    return count;
  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
  } 3
  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)

Other 2004 FR Questions | Back to Contents

Copyright © 2004 by Skylight Publishing