Correcting an Array Traversal Loop
The following code segment is intended to count the number of strings in the animals array that contain str as a substring, and then print the result. Assume that the String variable str has been properly declared and initialized.
String[] animals = {"horse", "cow", "goat", "dog", "cat", "mouse"};
int count = 0;
for (int i = 0; i <= animals.length; i++)
{
if (animals[i].indexOf(str) >= 0)
{
count++;
}
}
System.out.println(count);
Which of the following changes must be made for the code segment to work as intended?
A
The condition in the if statement should be changed to animals[i].equals(str).
B
The Boolean expression in the for loop header should be changed to i < animals.length.
C
The Boolean expression in the for loop header should be changed to i < animals.length - 1.
D
The condition in the if statement should be changed to animals[i].substring(str).
Question Leaderboard
Not enough data yet to show leaderboard.
