Learn AP Comp Sci

Problem of the Day

Friday, May 15, 2026


Problem:

The RandomCookieJar class keeps track of a random number of cookies, described by a String name: "chocolate chip", "sugar", "oatmeal", etc. A partial listing of the RandomCookieJar class is given here.

public class RandomCookieJar
{
private ArrayList<String> cookies;

/* constructor and methods not shown */

}

The fillJar method is used to add cookies to the jar as described below.

/**
* Fills the cookie jar with a specified number of cookies selected
* randomly from a list.
* @param cookieList an Array of cookies available to fill jar
* @param amount the total number of cookies to add to the jar
* PRECONDITION cookieList has at least one type of cookie
*/
public void fillJar(String[] cookieList, int amount)
{

/* missing code */

}

Which code should be used to replace /* missing code */ so the method will work as described?


  1. for (int i = 0; i < cookieList.length; i++)
    {
    cookies.add( cookieList[i] );
    }

  2. for (int i = 0; i < amount; i++)
    {
    cookies.add(cookieList[ (int) (Math.random() * cookieList.length) ] );
    }

  3. for (int i = 0; i < amount - 1; i++)
    {
    cookies.add(cookieList[ (int) (Math.random() * cookieList.length) ] );
    }

  4. for (int i = 0; i < amount; i++)
    {
    cookies.add(cookieList[ (int) (Math.random() * cookieList.size()) ] );
    }

  5. for (int i = 0; i < amount; i++)
    {
    cookies.add(cookieList[ (Math.random() * cookieList.length) ] );
    }

Show solution:

The correct answer is b. The loop needs to run amount times (as written in choices b through e), and each time, a random cookie selected from the Strings given in cookieList selected. The code to select a random element from cookieList is correctly written in choice (b).