Learn AP Comp Sci

Problem of the Day

Friday, March 1, 2024


Problem:

A String Array is declared and initialized as follows:

String[] words = {"alpha", "beta", "gamma"};

The boolean method check is shown here:

public static boolean check(String word)
{
for (int i = 1; i < word.length(); i++)
{
if (word.substring(i, i + 1).equals(word.substring(i - 1, i)))
return true;
}
return false;
}

Which words will produce a return value of true from the check method?

  1. "alpha" only
  2. "beta" only
  3. "gamma" only
  4. "alpha" and "beta" only
  5. "alpha" and "gamma" only

Show solution:

The correct answer is c. The check method loops through the string, and returns true if it finds two adjacent characters (at positions i and i - 1) that are the same. The word "gamma" is the only string that meets this requirement.