Word.java.html

  1  /**
  2     This class describes words in a document. There are a couple
  3     of bugs in this class.
  4  */
  5  public class Word
  6  {
  7     private String text;
  8  
  9     /**
 10        Constructs a word by removing leading and trailing non-
 11        letter characters, such as punctuation marks.
 12        @param s the input string
 13     */
 14     public Word(String s)
 15     {
 16        int i = 0;
 17        while (i < s.length() && !Character.isLetter(s.charAt(i)))
 18        {
 19           i++;
 20        }
 21        int j = s.length() - 1;
 22        while (j > i && !Character.isLetter(s.charAt(j)))
 23        {
 24           j--;
 25        }
 26        text = s.substring(i, j);      
 27     }
 28  
 29     /**
 30        Returns the text of the word, after removal of the
 31        leading and trailing non-letter characters.
 32        @return the text of the word
 33     */
 34     public String getText()
 35     {
 36        return text;
 37     }
 38  
 39     /**
 40        Counts the syllables in the word.
 41        @return the syllable count
 42     */
 43     public int countSyllables()
 44     {
 45        int count = 0;
 46        int end = text.length() - 1;
 47        if (end < 0) { return 0; } // The empty string has no syllables
 48  
 49        // An e at the end of the word doesn't count as a vowel
 50        char ch = text.charAt(end);
 51        if (ch == 'e' || ch == 'E') { end--; }
 52  
 53        boolean insideVowelGroup = false;
 54        for (int i = 0; i <= end; i++)
 55        {
 56           ch = text.charAt(i);
 57           String vowels = "aeiouyAEIOUY";
 58           if (vowels.indexOf(ch) >= 0) 
 59           {
 60              // ch is a vowel
 61              if (!insideVowelGroup)
 62              {
 63                 // Start of new vowel group
 64                 count++; 
 65                 insideVowelGroup = true;
 66              }
 67           }
 68        }
 69  
 70        // Every word has at least one syllable
 71        if (count == 0) { count = 1; }
 72  
 73        return count;      
 74     }
 75  }