Java Reference
In-Depth Information
Partially Filled Arrays
Often the exact size needed for an array is not known when a program is written or
the size may vary from one run of the program to another. One common and easy
way to handle this situation is to declare the array to be of the largest size the program
could possibly need. The program is then free to use as much or as little of the array
as needed.
Partially filled arrays require some care. The program must keep track of how
much of the array is used and must not reference any indexed variable that has not
been given a meaningful value. The program in Display 6.4 illustrates this point. It
reads in a list of golf scores and shows how much each score differs from the average.
This program will work for lists as short as 1 score, as long as 10 scores, and of any
length in between. The scores are stored in the array score , which has 10 indexed
variables, but the program uses only as much of the array as it needs. The variable
numberUsed keeps track of how many elements are stored in the array. The elements
(that is, the scores) are stored in positions score[0] through score[numberUsed - 1 ].
The details are very similar to what they would be if numberUsed were score.length
and the entire array were used. Note that the variable numberUsed usually must be an
argument to any method that manipulates the partially filled array. For example, the
methods showDifference and computeAverage use the argument numberUsed to
ensure that only meaningful array indices are used.
partially
filled array
Display 6.4
Partially Filled Array (part 1 of 3)
Contrary to normal practice, this allows fractional scores,
such as 71.5. However, this makes it a better example for our
purposes. (Anyway, when I play golf, losing a ball is only half a
stroke penalty. Try it sometime.)
1 import java.util.Scanner;
2 public class GolfScores
3 {
4 public static final int MAX_NUMBER_SCORES = 10;
5 /**
6 Shows differences between each of a list of golf scores and their
average.
7 */
8 public static void main(String[] args)
9 {
10 double [] score = new double [MAX_NUMBER_SCORES];
11 int numberUsed = 0;
12 System.out.println("This program reads golf scores and shows");
13 System.out.println("how much each differs from the average.");
14 System.out.println("Enter golf scores:");
15 numberUsed = fillArray(score);
16 showDifference(score, numberUsed);
17 }
(continued)
 
Search WWH ::




Custom Search