Java Reference
In-Depth Information
This is almost the same line of code you executed before. The variable is still
declared to be of type double[] , but in constructing the array, you requested 100
elements instead of 3, which constructs a much larger array:
[0]
[1]
[2]
[3]
[4]
[...]
[99]
temperature
0.0
0.0
0.0
0.0
0.0
...
0.0
Notice that the highest index is 99 rather than 100 because of zero-based indexing.
You are not restricted to using simple literal values inside the brackets. You can
use any integer expression. This flexibility allows you to combine arrays with loops,
which greatly simplifies the code you write. For example, suppose you want to read a
series of temperatures from a Scanner . You could read each value individually:
temperature[0] = input.nextDouble();
temperature[1] = input.nextDouble();
temperature[2] = input.nextDouble();
...
temperature[99] = input.nextDouble();
But since the only thing that changes from one statement to the next is the index,
you can capture this pattern in a for loop with a control variable that takes on the
values 0 to 99 :
for (int i = 0; i < 100; i++) {
temperature[i] = input.nextDouble();
}
This is a very concise way to initialize all the elements of the array. The preceding code
works when the array has a length of 100, but you can change this to accommodate an
array of a different length. Java provides a useful mechanism for making this code more
general. Each array keeps track of its own length. You're using the variable temperature
to refer to your array, which means you can ask for temperature.length to find out
the length of the array. By using temperature.length in the for loop test instead of
the specific value 100, you make your code more general:
for (int i = 0; i < temperature.length; i++) {
temperature[i] = input.nextDouble();
}
Notice that the array convention is different from the String convention. When
you are working with a String variable s , you ask for the length of the String by
referring to s.length() . When you are working with an array variable, you don't
Search WWH ::




Custom Search