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?
for (int i = 0; i < cookieList.length; i++)
{
cookies.add( cookieList[i] );
}for (int i = 0; i < amount; i++)
{
cookies.add(cookieList[ (int) (Math.random() * cookieList.length) ] );
}for (int i = 0; i < amount - 1; i++)
{
cookies.add(cookieList[ (int) (Math.random() * cookieList.length) ] );
}for (int i = 0; i < amount; i++)
{
cookies.add(cookieList[ (int) (Math.random() * cookieList.size()) ] );
}for (int i = 0; i < amount; i++)
{
cookies.add(cookieList[ (Math.random() * cookieList.length) ] );
}
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).