Trio is #4 from the from the 2014 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap14_frq_computer_science_a.pdf

Trio class

public class Trio implements MenuItem
{
    private Sandwich sandwich;
    private Salad salad;
    private Drink drink;

    public Trio(Sandwich sand, Salad sal, Drink dr)
    {
        sandwich = sand;
        salad = sal;
        drink = dr;
    }

    public String getName()
    {
        return sandwich.getName() + "/" + salad.getName() + "/" + drink.getName() + " Trio";
    }

    public double getPrice()
    {
        MenuItem cheapest = sandwich;

        if(salad.getPrice() < cheapest.getPrice())
            cheapest = salad;

        if(drink.getPrice() < cheapest.getPrice())
            cheapest = drink;

        return sandwich.getPrice() + salad.getPrice() + drink.getPrice() - cheapest.getPrice();
    }
}

See Class writing order for a technique to respond to AP CS FR that request an entire class.

Writing getPrice by finding the minimum of the 3 prices allows use of the standard algorithm to find the minimum. The standard algorithm is to keep track of the minimum so far and update it each time a new minimum is found. This is true whether the values are in an array, in individual variables, or being accepted as part of a stream.

See Finding the minimum or maximum.

2014 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Trio