Java Reference
In-Depth Information
We 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, we 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 we 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, we could use any index value here since, as
we have seen, they all return the same value, 365.
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
elements in the first dimension with the statement:
samples = new float[6][]; // Define 6 elements, each is an array
The variable samples 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 arrays. Obviously 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 wanted 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 could define the arrays in a loop:
for(int i = 0; i < samples.length; i++)
samples[i] = new float[i+1]; // Allocate each array
The effect of this is to produce an array layout that is shown in the diagram below.
Search WWH ::




Custom Search