Java Reference
In-Depth Information
EXAMPLE: (continued)
System.out.println(
"ERROR: Trying to average 0 numbers.");
System.out.println("computeAverage returns 0.");
return 0;
}
}
This is not likely to produce a noticeable difference in the efficiency of the program
in Display 6.6, but if the number of elements in the PartiallyFilledArray were
large so that the for loop would be executed many times, it might make a difference
in a situation where efficiency is critical.
Display 6.5 Partially Filled Array Class (part 1 of 4)
1 /**
2 Class for a partially filled array of doubles. The class enforces the
3 following invariant: All elements are at the beginning of the array in
4 locations 0, 1, 2, and so forth up to a highest index with no gaps.
5 */
6 public class PartiallyFilledArray
7{
8
private int maxNumberElements; //Same as a.length
9
private double [] a;
10
private int numberUsed; //Number of indices currently in use
11
/**
12
Sets the maximum number of allowable elements to 10.
13
*/
14
PartiallyFilledArray()
15
{
16
maxNumberElements = 10;
17
a = new double [maxNumberElements];
18
numberUsed = 0;
19
}
20
/**
21
Precondition arraySize > 0.
22
*/
23
PartiallyFilledArray( int arraySize)
24
{
25
if (arraySize <= 0)
26
{
27
System.out.println("Error Array size zero or negative.");
28
System.exit(0);
29
}
(continued)
Search WWH ::




Custom Search