← All free-response questionsQuestion 1 · Methods and Control Structures · 7 points
Parking Garage
A city garage charges a different rate for each hour of the day. The Garage class computes fees and formats license plates.
public class Garage
{
/** Returns the cost in dollars to park during the given hour.
* Precondition: 0 <= hour <= 23
*/
public int hourlyRate(int hour)
{ /* implementation not shown */ }
/** Returns the fee for parking from startHour up to,
* but not including, endHour.
* Precondition: 0 <= startHour < endHour <= 24
*/
public int totalFee(int startHour, int endHour)
{ /* to be implemented in part (a) */ }
/** Returns plate with all dashes removed and a single dash
* inserted after the third character.
* Precondition: plate has at least 4 non-dash characters
*/
public static String formatPlate(String plate)
{ /* to be implemented in part (b) */ }
}Part (a)
4 pointsWrite totalFee. Add up hourlyRate(h) for each hour from startHour to endHour - 1, with one discount: after the driver has paid for 3 hours, every later hour costs half its rate (use integer division). Hours with a rate of 0 are free and don't count toward the 3 paid hours.
Suppose the rates for hours 8 through 13 are as follows.
| Hour | 8 | 9 | 10 | 11 | 12 | 13 |
|---|---|---|---|---|---|---|
| Rate | 4 | 0 | 6 | 6 | 5 | 3 |
totalFee(8, 14) returns 4 + 0 + 6 + 6 + 5/2 + 3/2 = 19. totalFee(10, 12) returns 12.
Tab inserts spaces. Drafts save as you type.
Part (b)
3 pointsWrite formatPlate. It removes every dash from plate, then inserts a single dash after the third remaining character.
| Call | Returns |
|---|---|
formatPlate("AB-C12-3") | "ABC-123" |
formatPlate("XYZ9") | "XYZ-9" |
formatPlate("-7-7-7-A-") | "777-A" |
Tab inserts spaces. Drafts save as you type.
Self-score
0 / 7