?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Easy

Print Array Elements Using Math.random()

APCSA-LDF1M4

Consider the following code segment.

ArrayList<String> list = new ArrayList<String>();
list.add("beautiful");
list.add("pretty");
list.add("gorgeous");
list.add("stunning");
list.add("attractive");

int w=1;
while (w<=list.size())
{
    System.out.println(list.get((int) (Math.random()*5)));
    w++;
}

Which of the following BEST describes the output from this code segment?

A

It will throw an IndexOutOfBoundsException.

B

It will print the first element on five consecutive lines.

C

It will loop five times and randomly select an element each time through the loop that it prints to the console.

D

It will randomly print four of the elements, selecting from position 1 to position 4.

E

It will loop four times and randomly select an element each time through the loop that it prints to the console.