Guest User

Untitled

a guest
Jan 23rd, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. public class Word
  2. {
  3.     private String theWord; // the word converted to lowercase
  4.      private String theWordOriginal; //the original word
  5.     private static final String vowels = "aeiouy";
  6.    
  7.     Word(String w)
  8.     {
  9.         theWord = w.toLowerCase();
  10.           theWordOriginal = w;
  11.     }
  12.    
  13.     //-----------------------------------------------------------------
  14.     // Things to note
  15.     // 1. e endings ignored
  16.     // 2. consecutive vowels count as one syllable
  17.     // 3. words of length three or shorter count as a single syllable
  18.     //-----------------------------------------------------------------
  19.     public int countSyllables()
  20.     {
  21.         int syllables = 0;
  22.  
  23.         // check if word is of length 3
  24.         if( theWord.length() <= 3 )
  25.         {
  26.             syllables = theWord.length() > 0;
  27.             return syllables;
  28.         }
  29.        
  30.         // prune the word to ignore 'e' at the end
  31.         String prunedWord;
  32.         if( theWord.endsWith("e") )
  33.             prunedWord = theWord.substring(0, theWord.length()-2); // if last letter is an e, remove it and then do calculation
  34.         else
  35.             prunedWord = theWord;  // else, we just use the string as is
  36.        
  37.         /*
  38.             Now go thru each character
  39.             if last character is not a vowel and current one is
  40.                 increment syllable count
  41.             save current vowel state in lastIsVowel
  42.         */
  43.        
  44.         boolean lastIsVowel;
  45.         for(int i = 0, len = prunedWord.length(); i < len; i++)
  46.         {
  47.                boolean curIsVowel = isVowel( prunedWord.charAt(i) );
  48.             if ( curIsVowel && !lastIsVowel ) syllables++;
  49.                lastIsVowel = curIsVowel;
  50.         }
  51.        
  52.         if( syllables == 0 ) syllables++;
  53.        
  54.         return syllables;
  55.     }
  56.     public String getWord()
  57.     {
  58.         return theWordOriginal;
  59.     }
  60.     static boolean isVowel(char ch)
  61.     {
  62.         return vowels.indexOf(ch) >= 0;
  63.     }
  64. }
Add Comment
Please, Sign In to add comment