?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

Debugging Code: Average Birds in ArrayList

APCSA-UEEAYV

Consider the following method:

// return the average number of characters of all the elements
// that contain the string "bird"
public static double averageBirds(ArrayList<String> animals)
{
     double sum=0;
     int count=0;
     for(int i=0; i<animals.size(); i++)
     {
          if(animals.indexOf("bird") >= 0)
          {
               sum+=animals.get(i).length();
               count++;
          }
     }
     return sum/count;
}

Which of the following BEST explains why the code will compile but will NOT return the correct result?

A

The count variable needs to be defined as a double.

B

The calculation of the average is incorrect.

C

The loop does not consider all the elements in the array list.

D

The sum variable is adding the number of elements in the array list.

E

The if statement is not determining whether the current element contains “bird”.