Problem overview
Version 6 summarises a whole class instead of grading each student. The scores are in a List<Integer> named scores: 92, 78, 85, 67, 74, 88, 91 and 58. The program computes three numbers and prints them on three lines: the highest score, the lowest score and the average, rounded down.
Highest: 92
Lowest: 58
Average: 79
The scores add up to 633, and there are 8 of them. The exact average is 79.125, and integer division gives 79.
Approach: two library calls and one running total
The highest and lowest values don't need a loop. The Collections class has max and min, which scan a collection and return the largest and smallest element.
The average needs the sum, and for that the program uses a running total. It starts at 0, a loop adds each score in turn, and when the loop ends the variable holds the sum of all the scores. Dividing by scores.size(), the number of elements, gives the average. Both numbers are int, so the division drops the fraction.
Step by step
- Find the highest.
int highest = Collections.max(scores);returns the largest element. The method returns anInteger, and Java unboxes it into theintvariable. - Find the lowest.
Collections.min(scores)is the mirror image and returns the smallest element. - Start the total at 0. A running total starts at zero before any score has been counted.
- Add every score. A loop
for (int s : scores)takes each element ass, and the bodytotal += s;adds it. The body is one statement, so the loop fits on one line. - Compute the average.
total / scores.size()divides the sum by the count. On a list the count comes fromsize(), not fromlength, which is for arrays. - Print the three lines. Each line is a label followed by its value, such as
"Highest: " + highest, in the order highest, lowest, average.
The solution in Java
List<Integer> scores = Arrays.asList(92, 78, 85, 67, 74, 88, 91, 58);
int highest = Collections.max(scores);
int lowest = Collections.min(scores);
int total = 0;
for (int s : scores) total += s;
int average = total / scores.size();
System.out.println("Highest: " + highest);
System.out.println("Lowest: " + lowest);
System.out.println("Average: " + average);
The Java details worth a closer look:
Arrays.asList. It wraps the values in a list of fixed size. You can read elements and replace them, butscores.add(1)throwsUnsupportedOperationException. This lesson only reads the list, so that is fine.- Lists hold objects. The type is
List<Integer>, notList<int>. In the loop,int sunboxes eachIntegerautomatically. - Integer division.
total / scores.size()isint / int, so the result is 79, not 79.125. Casting the result afterwards doesn't help:(double) (total / scores.size())is 79.0, because the division was already done in integers. Casting one operand first,(double) total / scores.size(), gives 79.125, but this lesson wants the rounded-down whole number. - The one-line loop. Without braces a
forloop runs only the single statement after it. That is enough here. With more statements the braces become necessary.
Complexity
Time: O(n) for n scores. Collections.max, Collections.min and the summing loop each make one pass over the list, so the work is three passes, which is still linear.
Space: O(1) beyond the list. The program stores a few int variables.
Edge cases and common mistakes
- An empty list.
Collections.maxon an empty list throwsNoSuchElementException, and so doesmin. Dividing the total, 0, bysize(), also 0, throwsArithmeticException: / by zero. The lesson's list always has elements. - One element. A list holding only 5 has the same highest, lowest and average: all three are 5.
- Starting a hand-written maximum at 0. If you search for the highest with your own loop and start the variable at 0, a list of negative numbers never beats it. For -5, -2 and -9 that gives 0 instead of -2.
Collections.maxavoids this problem. - Forgetting to start
totalat 0. A local variable has no default value, and Java won't compile a+=on a variable that was never assigned. - Using
lengthon a list. Arrays havelength, and lists havesize(). - Dividing by a fixed number. Writing
/ 8gives the right answer for this list only. Usingscores.size()keeps the code correct when the list changes.
Testing
- The starting list prints
Highest: 92,Lowest: 58andAverage: 79. - A list holding only 5 prints 5 on all three lines.
