Java Reference
In-Depth Information
Display 6.6
Display 6.4 Redone Using the Class PartiallyFilledArray (part 2 of 2)
41 /**
42 Returns the average of numbers in the PartiallyFilledArray a.
43 */
44 public static double computeAverage(PartiallyFilledArray a)
45 {
46 double total = 0;
47 for ( int index = 0; index < a.getNumberOfElements(); index++)
48 total = total + a.getElement(index);
49 if (a.getNumberOfElements() > 0)
50 {
51 return (total/a.getNumberOfElements());
52 }
53 else
54 {
55 System.out.println("ERROR: Trying to average 0 numbers.");
56 System.out.println("computeAverage returns 0.");
57 return 0;
58 }
59 }
60 /**
61 Gives screen output showing how much each of the
62 elements in the PartiallyFilledArray a differ from the average.
63 */
64 public static void showDifference(PartiallyFilledArray a)
65 {
66 double average = computeAverage(a);
67 System.out.println("Average of the " + a.getNumberOfElements()
68 + " scores = " + average);
69 System.out.println("The scores are:");
70 for ( int index = 0; index < a.getNumberOfElements(); index++)
71 System.out.println(a.getElement(index)
+ "differs from average by"
72 + (a.getElement(index)- average));
73 }
74 }
through all the elements of a collection object with this kind of for loop, because these
collection classes normally do not have indices associated with their elements, as an
array does. 4 However, starting with version 5.0, Java has added a new kind of for loop
that can cycle through all the elements in a collection even though there are no indices
4 You can construct a similar for loop using something called an iterator in place of the array index but
we will not go into that until later in this topic.
 
 
Search WWH ::




Custom Search