|
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
Suppose we want to write a program that deals with annual rainfall in
the New River Valley.
One way would be to have twelve different
Clearly,
declaring, initializing, and processing
twelve different
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; |
A
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.
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); |
1You might think
the syntax would be
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
©2010, Ian Barland, Radford University Last modified 2010.Nov.15 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |