Java Reference
In-Depth Information
}
// Output the average temperature for the current location
System.out.println("Average temperature at location "
+ (++location) + " = " + average/
(float)temperatures.length);
}
The outer loop iterates over the elements in the array of arrays, so the loop variable temperatures refer-
ence each of the one-dimensional arrays in temperature in turn. The type of the temperatures variable
is float[] because it stores a reference to a one-dimensional array from the array of one-dimensional ar-
rays, temperature . As in the earlier example, the explicit cast for temperatures.length to type float
is not strictly necessary.
The inner for loop iterates over the elements in the array that is currently referenced by temperatures ,
and the loop variable t is assigned the value of each element from the temperatures in turn. You have to
define an extra variable, location , to record the location number as this was previously provided by the
loop variable i , which is not present in this version. You increment the value of location in the output
statement using the prefix form of the increment operator so the location values are 1, 2, 3, and so on.
Arrays of Arrays of Varying Length
When you create an array of arrays, the arrays in the array do not need to be all the same length. You could
declare an array variable, samples , with the statement:
float[][] samples; // Declare an array of arrays
This declares the array object samples to be of type float[][] . You can then define the number of ele-
ments in the first dimension with the statement:
samples = new float[6][]; // Define 6 elements, each is an array
The samples variable now references an array with six elements, each of which can hold a reference to a
one-dimensional array. You can define these arrays individually if you want:
samples[2] = new float[6]; // The 3rd array has 6 elements
samples[5] = new float[101]; // The 6th array has 101 elements
This defines two of the six possible one-dimensional arrays that can be referenced through elements of
the samples array. The third element in the samples array now references an array of 6 elements of type
float , and the sixth element of the samples array references an array of 101 elements of type float . Obvi-
ously, you cannot use an array until it has been defined, but you could conceivably use these two and define
the others later — not a likely approach, though!
If you want the array samples to have a triangular shape, with one element in the first row, two elements
in the second row, three in the third row, and so on, you can define the arrays in a loop:
for(int i = 0; i < samples.length; ++i) {
samples[i] = new float[i+1]; // Allocate each array
Search WWH ::




Custom Search