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           i++;
 19        int j = s.length() - 1;
 20        while (j > i && !Character.isLetter(s.charAt(j)))
 21           j--;
 22        text = s.substring(i, j);      
 23     }
 24  
 25     /**
 26        Returns the text of the word, after removal of the
 27        leading and trailing non-letter characters.
 28        @return the text of the word
 29     */
 30     public String getText()
 31     {
 32        return text;
 33     }
 34  
 35     /**
 36        Counts the syllables in the word.
 37        @return the syllable count
 38     */
 39     public int countSyllables()
 40     {
 41        int count = 0;
 42        int end = text.length() - 1;
 43        if (end < 0) return 0; // The empty string has no syllables
 44  
 45        // An e at the end of the word doesn't count as a vowel
 46        char ch = Character.toLowerCase(text.charAt(end));
 47        if (ch == 'e') end--;
 48  
 49        boolean insideVowelGroup = false;
 50        for (int i = 0; i <= end; i++)
 51        {
 52           ch = Character.toLowerCase(text.charAt(i));
 53           String vowels = "aeiouy";
 54           if (vowels.indexOf(ch) >= 0) 
 55           {
 56              // ch is a vowel
 57              if (!insideVowelGroup)
 58              {
 59                 // Start of new vowel group
 60                 count++; 
 61                 insideVowelGroup = true;
 62              }
 63           }
 64        }
 65  
 66        // Every word has at least one syllable
 67        if (count == 0) 
 68           count = 1;
 69  
 70        return count;      
 71     }
 72  }