Codiqo

Learn Java · lesson 29 of 61 · about 10 minutes

Project: Rating Statistics

Report what the audience thought: read ratings into an array, and give the average and the median from static methods.

What you'll learn

  • Fill an array from input
  • Write focused static methods
  • Calculate a median by sorting a copy

The audience's ratings

After the film, the audience rates it out of 10. The desk reads how many ratings there are, makes an array exactly that size with new int[votes], and fills it. Two static methods do the sums: average adds them up, and median finds the middle one. To find the middle, median sorts a copy made with Arrays.copyOf, so the ratings are still in the order they were given when the desk prints them.

The plan

1. Read how many scores, then read them into an array
2. Static methods work out the average, median and pass count
3. The median sorts a copy (Arrays.copyOf) so the original order is kept

Step 1: an average from an array

public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 45, 90};
        int total = 0;
        for (int x : scores) total += x;
        System.out.printf("Average: %.1f%n", (double) total / scores.length);
    }
}

Output

Average: 69.0

Score statistics

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static double average(int[] a) {
        int total = 0;
        for (int x : a) total += x;
        return (double) total / a.length;
    }

    static double median(int[] a) {
        int[] s = Arrays.copyOf(a, a.length);
        Arrays.sort(s);
        int n = s.length;
        return n % 2 == 1 ? s[n / 2] : (s[n / 2 - 1] + s[n / 2]) / 2.0;
    }

    static int passes(int[] a) {
        int count = 0;
        for (int x : a) if (x >= 50) count++;
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] scores = new int[n];
        for (int i = 0; i < n; i++) scores[i] = in.nextInt();
        System.out.printf("Average: %.1f%n", average(scores));
        System.out.printf("Median:  %.1f%n", median(scores));
        System.out.println("Passed:  " + passes(scores) + "/" + n);
        System.out.println("Order kept: " + Arrays.toString(scores));
    }
}

Output

Average: 64.3
Median:  66.5
Passed:  4/6
Order kept: [72, 45, 90, 61, 38, 80]

Tip

new int[0] is allowed: an empty array with length 0. Dividing by its length would be dividing by 0, so check for no ratings first.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.