Learn AP Comp Sci

Problem of the Day


A boolean method check is shown here:

public static boolean check(String word)
String vowels = "aeiou";
return (vowels.indexOf(word.substring(0,1)) >= 0 &&
vowels.indexOf(word.substring(word.length() - 1)) < 0) ||
(vowels.indexOf(word.substring(0,1)) < 0 &&
vowels.indexOf(word.substring(word.length() - 1)) >= 0);

Under what conditions does the boolean method return the value true?

  1. When the first and last letters of the string are both vowels
  2. When the first letter is a vowel and the last letter is a consonant
  3. When the first letter is a consonant and the last letter is a vowel
  1. I only
  2. II only
  3. III only
  4. I or II only
  5. II or III only

Show solution:

The correct answer is e. The check method is looking for first and last letters that are either consonant-vowel or vowel-consonant, using the value of the indexOf. The method indexOf returns a positive value if a letter is found in the String vowels (and therefore a vowel), or a -1 result if the letter is not found in vowels (and therefore a consonant).