Learn AP Comp Sci

Problem of the Day

Thursday, December 18, 2025


Problem:

The String Array students holds the names of a series of students who are seated in order in a single line in a classroom.

String[] students = {"Aaron", "Bobby", "Caroline", "Darlene"};

... for example, represents four students seated left-to-right in the classroom.

What does the following code segment do?

ArrayList vals = new ArrayList();
for (int i = 0; i < students.length; i++) { vals.add(i); }
while (true)
{
int j = (int) (Math.random() * vals.size());
System.out.println("Work with " + students[vals.remove(j)]);
if (vals.size() == 0)
for (int i = 0; i < students.length; i++) { vals.add(i); }
}
  1. Chooses a random student from the list each time, possibly selecting the same student twice in a row
  2. Chooses a random student from the list each time, with no student selected twice before all students have been selected once
  3. Repeatedly goes through the list of students from left-to-right
  4. Repeatedly goes through the list of students from right-to-left

Show solution:

The correct answer is b. A separate ArrayList of the indices in the Array of students is maintained, and those indices are "crossed off" (removed) as they are randomly selected, ensuring that each student gets seen only once in a cycle. Once the ArrayList is empty, a new ArrayList of students is created and the process begins again.