Java Reference
In-Depth Information
For a fixed value for the second index in a two-dimensional array, varying the first index value is often
referred to as accessing a column of the array. Similarly, fixing the first index value and varying the second,
you access a row of the array. The reason for this terminology should be apparent from Figure 4-4 .
You could equally well have used two statements to create the last array, one to declare the array variable
and the other to define the array:
float [][] temperature; // Declare the array variable
temperature = new float[10][365]; // Create the array
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 of type
float .
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
To save you having to wander around 10 different locations armed with a thermometer, you'll generate
the temperatures as random values between −10 degrees and 35 degrees. This assumes you are recording
temperatures in degrees Celsius. If you prefer Fahrenheit, you could generate values from 14 degrees to
95 degrees 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[i].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);
Search WWH ::




Custom Search