☰ Contents Recipe for Success

Practice

Fill in each method header to match the example method calls at the bottom.
record ParkingSession(int minutesParked, int centsPerHour) {
{
return minutesParked * centsPerHour / 60;
}
{
return minutesParked > limitMinutes;
}
{
return Math.max(0, limitMinutes - minutesParked);
}
}
ParkingSession lunch = new ParkingSession(45, 300);
int lunchCost = lunch.costCents();
boolean lunchTooLong = lunch.isOverLimit(60);
int lunchLeft = lunch.minutesLeft(60);
We mentioned how sometimes it’s useful to pick a placeholder value before getting into a complex method body implementation. Pick a placeholder for each method so the program runs. It only has to be the right type, not the right answer.
record ParkingSession(int minutesParked, int centsPerHour) {
int costCents() { return ; }
boolean isOverLimit(int limitMinutes) { return ; }
double hoursParked() { return ; }
String receipt() { return ; }
Pict meterSign() { return ; }
}
Make streamflix a subscription that costs less than disney after 3 months, but more than disney after 12 months.
record Subscription(String name, int priceCents, int trialMonths) {
int costAfter(int months) {
return Math.max(0, months - trialMonths) * priceCents;
}
}
Subscription disney = new Subscription("Disney+", 2100, 1);
Subscription streamflix = ;
int disney3 = disney.costAfter(3);
int streamflix3 = streamflix.costAfter(3);
int disney12 = disney.costAfter(12);
int streamflix12 = streamflix.costAfter(12);

A student followed most of the recipe for a parking meter:

  1. Wrote the record: record ParkingSession(int minutes, int rate) {}
  2. Wrote the header with a placeholder, int costCents() { return 0; }, and checked that it runs.
  3. Filled in the body: return minutes * rate;
  4. Started a test, assertEquals(___, new ParkingSession(90, 300).costCents()), and got stuck: is 300 cents per minute or per hour? Is the answer 27000 or 450?

Which step did they skip that would have raised that question first?

  1. Writing example data and saying what it means in English
  2. Writing the method header
    They did write a header, in step 2.
  3. Using a placeholder so the program runs
    They did, in step 2, and it ran.
  4. Writing a helper method
    A helper would not tell them what rate means.
This discount method looks right, but some percentOff makes the “discounted” price higher than the original. Find one.
record CartItem(String name, int priceCents) {
int priceWithDiscount(int percentOff) {
return priceCents * (100 - percentOff) / 100;
}
}
CartItem mug = new CartItem("mug", 1000);
int percentOff = ;
int discounted = mug.priceWithDiscount(percentOff);
Change it so a negative percentOff counts as no discount.
record CartItem(String name, int priceCents) {
int priceWithDiscount(int percentOff) {
return priceCents * (100 - ) / 100;
}
}
CartItem mug = new CartItem("mug", 1000);
int noDiscount = mug.priceWithDiscount(-10);
int quarterOff = mug.priceWithDiscount(25);