Start learning free

LESSON 205 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in Scala: Grades by Subject with a TreeMap

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

val grades = scala.collection.mutable.TreeMap[String, Int]()
grades("Math") = 92
grades("English") = 78
grades("Science") = 85
grades("History") = 67

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Use a TreeMap - it iterates its keys in sorted order automatically.

val grades = scala.collection.mutable.TreeMap[String, Int]()
grades("Math") = 92
grades("English") = 78
grades("Science") = 85
grades("History") = 67

for (subject <- grades.keys) {
    val score = grades(subject)
    var grade = ""
    if (score >= 90) {
        grade = "A"
    } else if (score >= 80) {
        grade = "B"
    } else if (score >= 70) {
        grade = "C"
    } else if (score >= 60) {
        grade = "D"
    } else {
        grade = "F"
    }
    println(subject + ": " + grade)
}

STEP 1 OF 9
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in Scala, explained

    Problem overview

    Version 5 stores the scores in a map from subject name to score instead of two arrays. The starter code creates a scala.collection.mutable.TreeMap[String, Int] and fills it: Math is 92, English 78, Science 85 and History 67. The program prints each subject with its letter grade, in alphabetical order:

    English: C
    History: D
    Math: A
    Science: B
    

    The grading scale is unchanged: 90 and above is A, 80 to 89 B, 70 to 79 C, 60 to 69 D, anything lower F.

    Approach

    A map stores key-value pairs and finds a value from its key. Here the keys are the subjects and the values are the scores. The program loops over the keys, looks up each score and runs the same ladder as before.

    The order of the output is the interesting part. The subjects were inserted as Math, English, Science and History, but the output is alphabetical. That is the job of a TreeMap: it keeps its keys sorted, so walking over grades.keys visits English, History, Math and Science no matter how they were inserted. A hash-based map makes no promise about order, which is why the starter code chose a TreeMap.

    Step by step

    1. Loop over the keys. for (subject <- grades.keys) hands over one subject at a time, in sorted order. Close the brace right away.
    2. Look up the score. val score = grades(subject). Scala looks up a map with parentheses, as it indexes an array.
    3. Declare grade as a var holding empty text.
    4. Start the ladder with an if for 90 or more that sets "A".
    5. Add the branch for 80 or more, which sets "B".
    6. Add the branch for 70 or more, which sets "C".
    7. Add the branch for 60 or more, which sets "D".
    8. Finish with else for "F" and close the ladder.
    9. Print the subject, a colon, a space and the grade, inside the loop.

    The solution in Scala

    val grades = scala.collection.mutable.TreeMap[String, Int]()
    grades("Math") = 92
    grades("English") = 78
    grades("Science") = 85
    grades("History") = 67
    
    for (subject <- grades.keys) {
        val score = grades(subject)
        var grade = ""
        if (score >= 90) {
            grade = "A"
        } else if (score >= 80) {
            grade = "B"
        } else if (score >= 70) {
            grade = "C"
        } else if (score >= 60) {
            grade = "D"
        } else {
            grade = "F"
        }
        println(subject + ": " + grade)
    }
    

    What the loop visits

    Walking over the sorted keys, each pass looks up one score and prints one grade:

    subjectgrades(subject)printed
    English78English: C
    History67History: D
    Math92Math: A
    Science85Science: B

    The ladder itself is the same code as in the version for a list of students. Only the way the score is found changed: a key lookup replaces an index into an array, so there are no positions to keep in step.

    Working with a mutable map

    The statement writes grades("Math") = 92. On a mutable map that call adds the key if it is new and replaces the value if it already exists. Assigning grades("Math") = 50 later changes the stored score to 50 and leaves the size of the map at 4.

    grades(subject) throws NoSuchElementException if the key is missing. For the message key not found: Music that is what a lookup of an absent subject gives. When a key might be missing, use grades.get("Music"), which returns an Option: Some(92) for Math and None for Music. grades.getOrElse("Music", 0) returns 0 instead. In this lesson every key comes from grades.keys, so the plain lookup is safe.

    Printing the map itself shows the sorted order: TreeMap(English -> 78, History -> 67, Math -> 92, Science -> 85), and grades.keys is a SortedSet.

    The price of keeping the keys sorted is a little speed. A mutable TreeMap is a balanced tree, so a lookup or an insertion takes about log n steps, where a hash map takes roughly constant time. For four subjects the difference is invisible, and the ordered output is worth more here.

    Edge cases and common mistakes

    • Uppercase before lowercase. A TreeMap[String, Int] compares strings by character code, where every capital letter comes before every lowercase one. With the keys "Art", "art" and "Biology", the order is Art, Biology, art. The lesson's four subjects all start with a capital, so they sort as expected.
    • An empty map. The loop body never runs and nothing is printed.
    • Using a plain HashMap. The grades would still be right, but the lines could come out in any order and the lesson's tests expect alphabetical output.
    • Losing a subject by reusing a key. Putting two scores under the same name keeps only the last one, because keys are unique.
    • Boundary scores. Subjects with 55, 60 and 95 get F, D and A: a lower bound of 60 is inclusive, so 60 passes with a D.

    Testing

    Add a subject to the map and see where it lands: a new entry named Art appears first, before English, because the keys stay sorted. Change a score to 90 and the grade becomes A; change it to 59 and it becomes F. An empty map should print nothing at all.

    Key takeaways

    • A TreeMap keeps its keys sorted, so iterating over its keys gives alphabetical order.
    • map(key) reads a value and throws if the key is absent; get gives an Option.
    • On a mutable map, map(key) = value adds or replaces an entry.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free