← All free-response questionsQuestion 1 · Methods and Control Structures · 7 points
Rain Gauge
A weather station records daily rainfall. The RainGauge class gives access to the records.
public class RainGauge
{
/** Returns the rainfall in millimeters on the given day.
* Precondition: day >= 1
*/
private int getRainfall(int day)
{ /* implementation not shown */ }
/** Returns the length of the longest run of consecutive
* dry days (rainfall of 0) from day 1 to numDays, inclusive.
* Precondition: numDays >= 1
*/
public int longestDryStreak(int numDays)
{ /* to be implemented in part (a) */ }
/** Returns the initials of name, in uppercase order of appearance.
* Precondition: name contains words separated by single
* spaces, with no leading or trailing spaces.
*/
public static String initials(String name)
{ /* to be implemented in part (b) */ }
}Part (a)
4 pointsWrite the method longestDryStreak. It returns the length of the longest run of consecutive days with zero rainfall, from day 1 through day numDays. If there are no dry days, it returns 0.
Suppose getRainfall returns the following values for days 1 through 9.
| Day | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|
| Rainfall | 0 | 4 | 0 | 0 | 0 | 2 | 0 | 0 | 7 |
longestDryStreak(9) returns 3 (days 3–5). longestDryStreak(2) returns 1.
Tab inserts spaces. Drafts save as you type.
Part (b)
3 pointsWrite the static method initials. It returns a String made of the first character of each word in name, in order. Words are separated by single spaces.
| Call | Returns |
|---|---|
initials("Grace Brewster Hopper") | "GBH" |
initials("Alan Turing") | "AT" |
initials("Ada") | "A" |
Tab inserts spaces. Drafts save as you type.
Self-score
0 / 7