Java Reference
In-Depth Information
The first statement declares the array variable temperature for two-dimensional arrays of type float . The
second statement creates the array with ten elements, each of which is an array of 365 elements.
Let's exercise this two-dimensional array in a program to calculate the average annual temperature for
each location.
Try It Out - The Weather Fanatic
In the absence of real samples, we will generate the temperatures as random values between -10
°
and
35
. This assumes we are recording temperatures in degrees Celsius. If you prefer Fahrenheit you could
use 14
°
°
to 95
°
to cover the same range.
public class WeatherFan {
public static void main(String[] args) {
float[][] temperature = new float[10][365]; // Temperature array
// Generate random temperatures
for(int i = 0; i < temperature.length; i++) {
for(int j = 0; j < temperature[i].length; j++)
temperature[i][j] = (float)(45.0*Math.random() - 10.0);
}
// Calculate the average per location
for(int i = 0; i < temperature.length; i++) {
float average = 0.0f; // Place to store the average
for(int j = 0; j < temperature[0].length; j++)
average += temperature[i][j];
// Output the average temperature for the current location
System.out.println("Average temperature at location "
+ (i+1) + " = " + average/(float)temperature[i].length);
}
}
}
How It Works
After declaring the array temperature we 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 we use temperature[i].length to refer to the length of the second
dimension, 365. We could use any index value here; temperature[0].length would have been just
as good for all the elements, since the lengths of the rows of the array are all the same in this case.
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 us the range we require, -10.0 to 35.0.
Search WWH ::




Custom Search