Activity 4.39.1.
What type of loop is best for this problem?
https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year
CookieOrder
class is shown below.
public class CookieOrder
{
/** Constructs a new CookieOrder object */
public CookieOrder(String variety, int numBoxes)
{
/* implementation not shown */
}
/**
* @return the variety of cookie being ordered
*/
public String getVariety()
{
/* implementation not shown */
}
/**
* @return the number of boxes being ordered
*/
public int getNumBoxes()
{
/* implementation not shown */
}
// There may be instance variables, constructors, and methods that are not
// shown.
}
MasterOrder
class maintains a list of the cookies to be purchased. The declaration of the MasterOrder
class is shown below.
public class MasterOrder
{
/** The list of all cookie orders */
private List<CookieOrder> orders;
/** Constructs a new MasterOrder object */
public MasterOrder()
{
orders = new ArrayList<CookieOrder>();
}
/**
* Adds theOrder to the master order.
*
* @param theOrder the cookie order to add to the master order
*/
public void addOrder(CookieOrder theOrder)
{
orders.add(theOrder);
}
/**
* @return the sum of the number of boxes of all of the cookie orders
*/
public int getTotalBoxes()
{
/* to be implemented in part (a) */
}
// There may be instance variables, constructors, and methods that are not
// shown.
}
getTotalBoxes
method computes and returns the sum of the number of boxes of all cookie orders. If there are no cookie orders in the master order, the method returns 0.
public int getTotalBoxes()
{
for (CookieOrder co : this.orders)
{
int sum = sum + co.getNumBoxes();
}
return sum;
}
getTotalBoxes
below contains the correct code for one solution to this problem, but it is mixed up. Drag the needed code from the left to the right and put them in order with the correct indention so that the code would work correctly.
getTotalBoxes
below.