Java Reference
In-Depth Information
double[] samples = new double[50]; // An array of 50 double values
for(int i = 0; i < 50; i++)
samples[i] = 100.0*Math.random(); // Generate random values
To show that array elements can be used in exactly the same way as ordinary variables, you could write:
double result = (samples[10]*samples[0] -
Math.sqrt(samples[49]))/samples[29];
This is a totally arbitrary calculation of course. More sensibly, to compute the average of the values
stored in the samples array, you could write:
double average = 0.0; // Variable to hold the average
for(int i = 0; i < 50; i++)
average += samples[i]; // Sum all the elements
average /= 50; // Divide by the total number of elements
Within the loop we accumulate the sum of all the elements of the array samples in the variable
average . We then divide this sum by the number of elements.
Notice how we use the length of the array, 50, all over the place. It appears in the for loop, and in
floating point form as a divisor to calculate the average. When you use arrays you will often find that
references to the length of the array are strewn all through your code. And if you later want to change
the program, to handle 100 elements for instance, you need to be able to decide whether any particular
value of 50 in the code is actually the number of elements, and therefore should be changed to 100, or if
it is a value that just happens to be the same and should be left alone. Java helps you avoid this
problem, as we will now see.
Array Length
You can refer to the length of the array using length , a data member of the array object. For our
array samples , we can refer to its length as samples.length . We could use this to write the
calculation of the average as:
double average = 0.0; // Variable to hold the average
for(int i = 0; i < samples.length; i++)
average += samples[i]; // Sum all the elements
average /= samples.length; // Divide by the total number of elements
Now the code is independent of the number of array elements. If you change the number of elements in
the array, the code will automatically deal with that. You will also see in Chapter 6 that being able to
obtain the length of an array in this way is very convenient in the context of coding your own class
methods that process arrays. You should always use this approach when you need to refer to the length
of an array - never use explicit values.
Let's try out an array in an improved program to calculate prime numbers:
Search WWH ::




Custom Search