Java Reference
In-Depth Information
}
}
WeatherFan.java
When I ran the program, I got the following output:
Average temperature at location 1 = 12.2733345
Average temperature at location 2 = 12.012519
Average temperature at location 3 = 11.54522
Average temperature at location 4 = 12.490543
Average temperature at location 5 = 12.574791
Average temperature at location 6 = 11.950315
Average temperature at location 7 = 11.492908
Average temperature at location 8 = 13.176439
Average temperature at location 9 = 12.565457
Average temperature at location 10 = 12.981103
You should get different results.
How It Works
After declaring the array temperature you fill it with random values using nested for loops. Note how
temperature.length used in the outer loop refers to the length of the first dimension, 10 in this case.
In the inner loop you use temperature[i].length to refer to the length of the second dimension, 365.
You could use any index value here; temperature[0].length would have been just as good for all the
elements because the lengths of the rows of the array are all the same in this case. In the next section you
will learn how you create arrays with rows of varying length.
The Math.random() method generates a value of type double from 0.0 up to, but excluding, 1.0. This
value is multiplied by 45.0 in the expression for the temperature, which results in values between 0.0 and
45.0. Subtracting 10.0 from this value gives you the range you require, − 10.0 to 35.0.
You then use another pair of nested for loops, controlled in the same way as the first, to calculate the
averages of the stored temperatures. The outer loop iterates over the locations and the inner loop sums all
the temperature values for a given location. Before the execution of the inner loop, the variable average
is declared and initialized, and this is used to accumulate the sum of the temperatures for a location in the
inner loop. After the inner loop has been executed, you output the average temperature for each location,
identifying the locations by numbers 1 to 10, one more than the index value for each location. Note that
the parentheses around (i+1) here are essential. To get the average, you divide the variable average by
the number of samples, which is temperature[i].length , the length of the array holding temperatures
for the current location. Again, you could use any index value here because, as you have seen, they all
return the same value, 365.
You can write the nested loop to calculate the average temperatures as nested collection-based for loops,
like this:
int location = 0; // Location number
for(float[] temperatures : temperature) {
float average = 0.0f; // Place to store the average
for(float t : temperatures) {
average += t;
Search WWH ::




Custom Search