Complete the Sentence class below so that it implements the Measurable interface. The measure of a sentence should be the number of words. For example,

new Sentence("Mary had a little lamb.").getMeasure()

should return 5.

Complete the following file:

Sentence.java

public class Sentence implements Measurable { /** Constructs a sentence. @param text the text of the sentence. */ public Sentence(String text) { int n = text.length(); String punctuation = text.substring(n - 1, n); words = text.substring(0, n - 1).split("\\s+"); } /** Returns a word in this sentence. @param the index of the word @return the ith word or an empty string if i is < 0 or >= the number of words in this sentence */ public String getWord(int i) { if (i >= 0 && i < words.length) return words[i]; else return ""; } public String toString() { String r = ""; for (String w : words) { if (r.length() > 0) r += " "; r += w; } return r + punctuation; } // TODO: Do what it takes to implement the measurable interface // so that the measure of a sentence is the number of words. private String[] words; private String punctuation; }

Use the following files:

DataSet.java

/**
   Computes the average of a set of data values.
*/
public class DataSet
{
   /**
      Constructs an empty data set.
   */
   public DataSet()
   {
      sum = 0;
      count = 0;
      maximum = null;
   }

   /**
      Adds a data value to the data set.
      @param x a data value
   */
   public void add(Measurable x)
   {
      sum = sum + x.getMeasure();
      if (count == 0 || maximum.getMeasure() < x.getMeasure())
         maximum = x;
      count++;
   }

   /**
      Gets the average of the added data.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      if (count == 0) return 0;
      else return sum / count;
   }

   /**
      Gets the largest of the added data.
      @return the maximum or 0 if no data has been added
   */
   public Measurable getMaximum()
   {
      return maximum;
   }

   private double sum;
   private Measurable maximum;
   private int count;
}

Measurable.java

/**
   Describes any class whose objects can be measured.
*/
public interface Measurable
{
   /**
      Computes the measure of the object.
      @return the measure
   */
   double getMeasure();
}

SentenceTester.java

/**
   This program tests adding sentences to the DataSet class.
*/
public class SentenceTester
{
   public static void main(String[] args)
   {
      DataSet data = new DataSet();

      data.add(new Sentence("Mary had a little lamb."));
      data.add(new Sentence("Its face was white as snow."));
      data.add(new Sentence("And everywhere that Mary went,"));
      data.add(new Sentence("The lamb was sure to go."));

      System.out.println("Average measure: " 
            + data.getAverage());
      System.out.println("Expected: 5.5");
   }
}