typestar

grade_report.java in Java

A gradebook in one file: averages, letter grades and a summary.

// grade_report: per-student averages, letter grades, a class summary
import java.util.LinkedHashMap;
import java.util.stream.IntStream;

class GradeReport {
    public static void main(String[] args) {
        var scores = new LinkedHashMap<String, int[]>();
        scores.put("Ada", new int[] { 92, 88, 95 });
        scores.put("Alan", new int[] { 78, 85, 80 });
        scores.put("Grace", new int[] { 90, 91, 86 });
        scores.put("Edsger", new int[] { 70, 65, 74 });

        System.out.println("student    avg  grade");
        var classTotal = 0.0;
        for (var entry : scores.entrySet()) {
            var avg = IntStream.of(entry.getValue()).average().orElse(0);
            classTotal += avg;
            System.out.printf("%-9s %5.1f  %s%n",
                              entry.getKey(), avg, letter(avg));
        }
        System.out.printf("%nclass average %.1f%n",
                          classTotal / scores.size());
    }

    static String letter(double avg) {
        if (avg >= 90) return "A";
        if (avg >= 80) return "B";
        if (avg >= 70) return "C";
        return "F";
    }
}

How it works

  1. A LinkedHashMap of score arrays keeps insertion order.
  2. IntStream.average collapses each student's scores.
  3. The letter helper maps averages; printf aligns the table.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
903
Tokens
272
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 181 seconds.

Type this snippet

Step 2 of 2 in Encore, step 29 of 29 in Language basics.

← Previous