Advertisement
advictoriam

Untitled

Feb 5th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1. /*
  2.   TODO: Implement the Doublable interface. A word is doubled by
  3.   repeating it. For example, new Word("Java").makeDouble() should
  4.   return a word containing "JavaJava".
  5.  
  6.   This is the Word class from ch06/debugger (with the bugs fixed).
  7. */
  8.  
  9.  
  10. /**
  11.    This class describes words in a document.
  12. */
  13. public class Word implements Doublable
  14. {
  15.    public Doublable makeDouble()
  16.    {
  17.       Word w = new Word(String.format("%s%s", text, text));
  18.       return w;
  19.    }
  20.    /**
  21.       Constructs a word by removing leading and trailing non-
  22.       letter characters, such as punctuation marks.
  23.       @param s the input string
  24.    */
  25.    public Word(String s)
  26.    {
  27.       int i = 0;
  28.       while (i < s.length() && !Character.isLetter(s.charAt(i)))
  29.          i++;
  30.       int j = s.length() - 1;
  31.       while (j > i && !Character.isLetter(s.charAt(j)))
  32.          j--;
  33.       text = s.substring(i, j + 1);      
  34.    }
  35.  
  36.    /**
  37.       Returns the text of the word, after removal of the
  38.       leading and trailing non-letter characters.
  39.       @return the text of the word
  40.    */
  41.    public String toString()
  42.    {
  43.       return text;
  44.    }
  45.  
  46.    /**
  47.       Counts the syllables in the word.
  48.       @return the syllable count
  49.    */
  50.    public int countSyllables()
  51.    {
  52.       int count = 0;
  53.       int end = text.length() - 1;
  54.       if (end < 0) return 0; // The empty string has no syllables
  55.  
  56.       // An e at the end of the word doesn't count as a vowel
  57.       char ch = Character.toLowerCase(text.charAt(end));
  58.       if (ch == 'e') end--;
  59.  
  60.       boolean insideVowelGroup = false;
  61.       for (int i = 0; i <= end; i++)
  62.       {
  63.          ch = Character.toLowerCase(text.charAt(i));
  64.          String vowels = "aeiouy";
  65.          if (vowels.indexOf(ch) >= 0)
  66.          {
  67.             // ch is a vowel
  68.             if (!insideVowelGroup)
  69.             {
  70.                // Start of new vowel group
  71.                count++;
  72.                insideVowelGroup = true;
  73.             }
  74.          }
  75.          else insideVowelGroup = false;
  76.       }
  77.  
  78.       // Every word has at least one syllable
  79.       if (count == 0)
  80.          count = 1;
  81.  
  82.       return count;      
  83.    }
  84.  
  85.    private String text;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement