Java Reference
In-Depth Information
The preceding program does a pretty good job. Here is a sample execution:
How many days' temperatures? 5
Day 1's high temp: 78
Day 2's high temp: 81
Day 3's high temp: 75
Day 4's high temp: 79
Day 5's high temp: 71
Average = 76.8
But how do you count how many days were above average? You could try to incor-
porate a comparison to the average temperature into the loop, but that won't work. The
problem is that you can't figure out the average until you've gone through all of the
data. That means you'll need to make a second pass through the data to figure out how
many days were above average. You can't do that with a Scanner , because a Scanner
has no “reset” option that allows you to see the data a second time. You'd have to
prompt the user to enter the temperature data a second time, which would be silly.
Fortunately, you can solve the problem with an array. As you read numbers in and
compute the cumulative sum, you can fill up an array that stores the temperatures.
Then you can use the array to make the second pass through the data.
In the previous temperature example you used an array of double values, but here
you want an array of int values. So, instead of declaring a variable of type double[] ,
declare a variable of type int[] . You're asking the user how many days of temperature
data to include, so you can construct the array right after you've read that information:
int numDays = console.nextInt();
int[] temps = new int[numDays];
Here is the old loop:
for (int i = 1; i <= numDays; i++) {
System.out.print("Day " + i + "'s high temp: ");
int next = console.nextInt();
sum += next;
}
Because you're using an array, you'll want to change this to a loop that starts at 0
to match the array indexing. But just because you're using zero-based indexing inside
the program doesn't mean that you have to confuse the user by asking for “Day 0's
high temp.” You can modify the println to prompt for day (i + 1) . Furthermore,
you no longer need the variable next because you'll be storing the values in the array
instead. So, the loop code becomes
for (int i = 0; i < numDays; i++) {
System.out.print("Day " + (i + 1) + "'s high temp: ");
Search WWH ::




Custom Search