AI Hints
Home›Java Tutorial›Two-Dimensional Arrays, Common Array Mistakes, Practice: Top Scores
Java · Lesson 54 of 120

Practice: Top Scores

Put module six together.

⏱ 2 min read▶ Video at 1:07:41🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module six together. Given a list of scores, print the average, and the top three, without changing the original list.

  • A list of scores
  • Average and top three
  • Keep the original

Top three scores

Your turn. Pause the video, and try this. Store seven scores in an array. Print the average, with one decimal. Then print the three highest scores, and finally the original array, unchanged. Here is one solution. A for each loop adds up the scores. We copy the array before sorting, so the original stays the same. Then a loop walks backwards from the end, to print the three highest. Ninety five, ninety one, and eighty eight.

✍️ Exercise: Top three scores

Print the average (1 decimal), the top three scores, and the original array unchanged.

Show hint

Sort a copy: Arrays.copyOf, then Arrays.sort

Show solution
Main.javajava
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 95, 64, 88, 91, 57, 79};
        int sum = 0;
        for (int s : scores) sum += s;
        System.out.printf("Average: %.1f%n", (double) sum / scores.length);
        int[] sorted = Arrays.copyOf(scores, scores.length);
        Arrays.sort(sorted);
        System.out.print("Top three:");
        for (int i = sorted.length - 1; i >= sorted.length - 3; i--) {
            System.out.print(" " + sorted[i]);
        }
        System.out.println();
        System.out.println("Original: " + Arrays.toString(scores));
    }
}
Output
Average: 78.0
Top three: 95 91 88
Original: [72, 95, 64, 88, 91, 57, 79]

What module six taught

Arrays hold many values of one type, numbered from zero. Create them with values, or with new. Loop with an index, or with for each. The Arrays class prints, sorts, copies, and searches. And two dimensional arrays hold grids.

keyvalue
Create{ } or new int[n]
Loopfor i, or for each
HelpersArrays.toString, sort, copyOf
Gridsint[][]

Summary

You can now work with lists of values. That's the end of module six. Next module, methods.

Key takeaways
  • Arrays
  • Loops over arrays
  • Arrays helpers
Next up: Defining Methods — name a block of code