Other 2016 FR Questions FR other years Be Prepared Home
A-1
Part (a)
public class RandomStringChooser
{
  private ArrayList<String> words;

  public RandomStringChooser(String[] wordArray)
  {
    words = new ArrayList<String>();
    for (String w : wordArray)
      words.add(w);
  }

  public String getNext()
  {
    if (words.size() == 0)
      return "NONE"; 1
    int i = (int)(Math.random() * words.size());
    return words.remove(i); 2
  }
} 3, 4
Notes:
  1. Must return "NONE" if the list is empty.
  2. Recall that remove(i) returns the element formerly at index i.
  3. Since the class implements a list, we could also derive this class from ArrayList<String>:
    public class RandomStringChooser extends ArrayList<String>
    {
      public RandomStringChooser(String[] wordArray)
      {
        for (String w : wordArray)
          add(w);
      }
    
      public String getNext()
      {
        if (size() == 0)
          return "NONE";
        int i = (int)(Math.random() * size());
        return remove(i);
      }
    }
  4. It is possible to implement this class using standard arrays instead of an ArrayList.  However, the code will be longer and more prone to errors.  You would have to either mark the elements already chosen or to rearrange the values in the array and keep track of the number of remaining elements — the functionality already provided in ArrayList.


Part (b)
  public RandomLetterChooser(String str)
  {
    super(getSingleLetters(str)); 1
  }
Notes:
  1. We have to somehow pass the array of letters to RandomStringChooser's constructor, and super must be the first statement in the subclass's constructor.


Other 2016 FR Questions | Back to Contents

Copyright © 2016 by Skylight Publishing
support@skylit.com