Java Reference
In-Depth Information
Display 6.4
Partially Filled Array
(part 2 of 3)
18
/**
19
Reads values into the array a. Returns the number of values placed
in the array a.
20
*/
21
public static int
fillArray(
double
[] a)
22 {
23 System.out.println("Enter up to " + a.length
24 + " nonnegative numbers.");
25 System.out.println("Mark the end of the list with a negative
number.");
26 Scanner keyboard =
new
Scanner(System.in);
27
28
double
next;
29
int
index = 0;
30 next = keyboard.nextDouble();
31
while
((next >= 0) && (index < a.length))
32 {
33 a[index] = next;
34 index++;
35 next = keyboard.nextDouble();
36
//index is the number of array indexed variables used so far.
37 }
38
//index is the total number of array indexed variables used.
39
if
(next >= 0)
40 System.out.println("Could only read in "
41 + a.length + " input values.");
42
return
index;
43 }
The value of
index
is the number of
values stored in the array.
44
/**
45
Precondition: numberUsed <= a.length.
46
a[0] through a[numberUsed-1] have values.
47
Returns the average of numbers a[0] through a[numberUsed-1].
48
*/
49
public static double
computeAverage(
double
[] a,
int
numberUsed)
50 {
51
double
total = 0;
52
for
(
int
index = 0; index < numberUsed; index++)
53 total = total + a[index];
54
if
(numberUsed > 0)
55 {
56
return
(total/numberUsed);
57 }
58
else
59 {
60 System.out.println("ERROR: Trying to average 0 numbers.");
61 System.out.println("computeAverage returns 0.");
62
return
0;
63 }
64 }