Java Reference
In-Depth Information
Display 14.3
Golf Score Program
(part 2 of 3)
21 {
22 System.out.println("Enter a list of nonnegative numbers.");
23 System.out.println(
"Mark the end of the list with a negative number.");
24 Scanner keyboard =
new
Scanner(System.in);
25
double
next;
26
int
index = 0;
27 next = keyboard.nextDouble();
28
while
(next >= 0)
29 {
30 a.add(next);
31 next = keyboard.nextDouble();
32 }
33 }
34
/**
35
Returns the average of numbers in a.
36
*/
37
public static double
computeAverage(ArrayList<Double> a)
38 {
39
double
total = 0;
40
for
(Double element : a)
41 total = total + element;
42
int
numberOfScores = a.size();
43
if
(numberOfScores > 0)
44 {
45
return
(total/numberOfScores);
46 }
47
else
48 {
49 System.out.println("ERROR: Trying to average 0 numbers.");
50 System.out.println("computeAverage returns 0.");
51
return
0;
52 }
53 }
Because of automatic boxing, we can treat
values of type
double
as if their type
were
Double
.
A for-each loop is the nicest way to
cycle through all the elements in an
ArrayList
.
54
/**
55
Gives screen output showing how much each of the elements
56
in a differ from their average
.
57
*/
58
public static void
showDifference(ArrayList<Double> a)
59 {
60
double
average = computeAverage(a);
61 System.out.println("Average of the " + a.size()
62 + " scores = " + average);
63 System.out.println("The scores are:");
64
for
(Double element : a)
65 System.out.println(element + " differs from average by "
66 + (element — average));
67 }
68 }
(continued)