Problem of the Day
Problem:
Consider the following method.
public static void mystery(String s)
{
for (int i = 0; i < s.length(); i++)
{
int value = (i + 3) % s.length();
System.out.print(s.substring(value, value + 1));
}
System.out.println();
}
What is printed as a result of the call mystery("infinity");
inityinf
ytinifni
infinity
finityin
The correct answer is a. The i
-loop runs once for every character in the string, but it prints out the letter three positions ahead of i
. The modulo operator %
allows the index to wrap around to the beginning of the word, when i + 3
extends beyond the last character.