Java: Programming - Rainfall Stats
Write a program to print rainfall statistics for one week
This program will read a series of seven rainfall measurements (integer number
of millimeters of rain, one each of the seven days).
It will then print the following statistics.
- Maximum. The largest amount of rain that fell in any one day.
- Average rainfall per day. Compute this as a floating point number.
Sample data and results
Sample input data
Here are some sample values. Of course, it should work for any values.
1
0
12
7
0
0
11
Sample output
Maximum rainfall = 12, Average rainfall = 4.428571428571429
You may format the output differently if you wish.
Some hints
- Loop. You will need a loop to count the seven days.
The natural kind of counting loop is a for loop.
Other kinds (while or do..while) can be used if you wish,
but for would be the number one choice of most programmers.
Inside the loop you will read the next rainfall number,
check to see if it's greater than the current maximum and record it as
the new maximum if it is, and add the
amount of rain to the total for the week.
- Variables. You will need a variable that contains the
current maximum amount of daily rainfall, as well as one that
has the running sum of total rainfall so far.
Iterative approach
As with all programs, you should use an iterative approach.
Exactly how much you do in every step is not so important as to
take small steps, and get each one running before continuing.
You might do something like the following.
- Start with a program that does nothing!
- Read one number and display it.
- Write a loop to read and display 7 numbers (but no computation).
- Create a variable for the sum of all rainfall, initialize it, and
add all the input values. Print at the end.
- Keep track of the maximum.
- You're done!
Extra (cancellation) Credit
If you have the program running, you can go for "cancellation" credit.
You can't get more than full credit, but this can cancel out any other points
off in the problem.
- If you're bothered by the excessive number of decimal places that are printed,
you might try using the DecimalFormat class. Look in the
textbook index to find where it's described.
- Check for negative values. Give an error message and stop the program.
- Print out how many rainless days there were in a row (2 for the sample data).