![]() |
![]() |
|
Suppose we want to write a program that deals with monthly rainfall in
the New River Valley.
One way would be to have twelve different
Clearly,
declaring, initializing, and processing
twelve different array of double
.
An array is a table of values, indexed starting from 0. For example, our twelve doubles could be handled as one object:
double[] rain; // Declare a variable: its type is *array*-of-double.
rain = new double[12]; // Initialize ("allocate") the array (but not the array's contents).
// We now have twelve variables:
// rain[0], rain[1], rain[2], ..., rain[11]
// which we must initialize ourselves:
rain[0] = 2.3;
rain[1] = 4.1;
rain[2] = 3.7;
|
and code pad will show the answer israin
<object reference> (; double-click on the small red object-reference to see the actual object. The array is, conceptually, an object with twelve fields, nameddouble[] )
,0
,1
, …2
. However, to get/set these fields we use square-brackets:11
A
;
we want to say something like
,
but instead we'll write
.
(Also: Unlike strings, arrays let us get and set the info stored
at a particular index.)
Keep looking at the object as we continue initializing the array contents:
rain[3] = 4.2; rain[4] = 0.0; rain[5] = 2.7; rain[6] = 0.0; |
programming tip: Always initialize all the entries of your array.
two things to remember: With regular variables, we had two steps: declare, then initialize. With arrays, we now have three steps: declare, initialize (allocate) the array itself, then initialize the contents of the array.
array-of-isdouble
In the code pad, we can continue on.
Suppose we want to calculate the the average value.
This sounds like a job for [what type of programming statment?]
Yes! -- a loop.
What do we need to set up for every loop?
Yes! An index-variable, and a so-far variable:
int i = 0;
double rainSoFar = 0.0;
while (i < ) {
rainSoFar = rainSoFar + rain[i];
i = i + 1;
}
|
We can put this exact same thing inside a method:
/** Calculate the average value in a given double[].
* @param data The array to find the average of.
* @return the average value of double[].
*/
static avg( ) {
int i = 0;
double sumSoFar = 0.0;
while (i < ) {
sumSoFar = sumSoFar + data[i];
i = i + 1;
}
return ;
}
|
double[] scores = new double[2];
scores[0] = 92.5;
scores[1] = 98.0;
Looper.avg(scores) // Assuming the above static method is inside a class 'Looper'
double[] silly = new double[0]; // Not a very useful array at all.
// Note: No contents need initializing, whew.
Looper.avg(silly);
|
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland |