ScrabbleTest.java Answers

Click here to go back to the questions
// ANSWERS:

//  Write the following methods in the ScrabbleTest class:

//  (1) A method public int countVowels(String word)
//  that counts the number of vowels in "word" and returns
//  the result.
// 

public int countVowels(String word)
{
   word = word.toLowerCase();
   int vowels = 0;
   for (int i=0; i<word.length(); i++)
   {
      if (word.charAt(i) == 'a' ||
          word.charAt(i) == 'e' ||
          word.charAt(i) == 'i' ||
          word.charAt(i) == 'o' ||
          word.charAt(i) == 'u') {
         vowels++;
      }
   }
   return vowels;
}
 
// 
//  (2) A similar method countConsonants that returns the
//  number of consonants in a word.
// 

public int countConsonants(String word)
{
   return word.length() - countVowels(word);
}

// 
//  (3) Add some code to the main method to test out
//  the first two methods.  Then run the class to
//  see if it works as it should.
// 

ScrabbleTest x = new ScrabbleTest();

System.out.println(x.countVowels("apple")); // should print 2
System.out.println(x.countConsonants("apple")); // should print 3

// 
//  (4) A method public int scoreWord(String word) that
//  returns the "scrabble score" of the argument "word"
//  according to the following scheme:

//  Vowels score 1 point each while all other letters score
//  10 points each.
// 

public int scoreWord(String word)
{
   return (1 * countVowels(word) +
           10 * countConsonants(word));
}

// 
//  (5) Add some code to the main method to test out the
//  scoreWord method.  Run the class.
// 

System.out.println(x.scoreWord("apple")); // should print 32

//