Scala Project: Gradebook
A gradebook is a program that stores student scores and reports each grade, the class average, and the top student. This project builds one from a Map, a def, and loops over sorted names.
A def turns a score into a grade
The if and else chain checks the score from the top grade down. A score of 85 gives a B, and 63 gives an F.
def letterGrade(score: Int): String =
if score >= 90 then "A"
else if score >= 80 then "B"
else if score >= 70 then "C"
else "F"
@main def main(): Unit =
println(letterGrade(85))
println(letterGrade(63))Sorted names print in order
The names come from the map keys, turned into a sorted list. The loop prints each name with its score lookup.
@main def main(): Unit =
val scores = Map("Maya" -> 92, "Leo" -> 78, "Ana" -> 85)
val names = scores.keys.toList.sorted
for name <- names do
println(s"$name: ${scores(name)}")Example
def letterGrade(score: Int): String =
if score >= 90 then "A"
else if score >= 80 then "B"
else if score >= 70 then "C"
else "F"
@main def main(): Unit =
val scores = Map("Maya" -> 92, "Leo" -> 78, "Ana" -> 85, "Sam" -> 64, "Zoe" -> 88)
val names = scores.keys.toList.sorted
for name <- names do
println(s"$name: ${scores(name)} (${letterGrade(scores(name))})")
val average = scores.values.sum.toDouble / scores.size
println(f"Class average: $average%.1f")
var topName = ""
var topScore = -1
for name <- names do
if scores(name) > topScore then
topScore = scores(name)
topName = name
println(s"Top student: $topName with $topScore")Key points
- Scores map: a Map holds each student name as a key and that student's score as the value.
- Grade def: a def turns a score into a letter grade with an if and else chain.
- Sorted names: keys.toList.sorted gives the student names in alphabetical order.
- Average: the scores are added up and divided by the number of students.
- Top student: a loop keeps the highest score seen so far and the name that goes with it.
In this example, the loop over the sorted names prints each student with the score lookup and its letter grade. The average divides the total of all scores, 407, by 5 students to give 81.4, and the last loop keeps replacing the top score until Maya with 92 remains.
Note
The program prints lookups and sorted names, never the Map itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
How does the gradebook get the student names in alphabetical order?