Start learning free

LESSON 174 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 - Subject to Grade Dictionary in Java

Practice

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

You start with:

TreeMap<String, Integer> grades = new TreeMap<>();
grades.put("Math", 92);
grades.put("English", 78);
grades.put("Science", 85);
grades.put("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.

TreeMap<String, Integer> grades = new TreeMap<>();
grades.put("Math", 92);
grades.put("English", 78);
grades.put("Science", 85);
grades.put("History", 67);

for (String subject : grades.keySet()) {
    int score = grades.get(subject);
    String 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";
    }
    System.out.println(subject + ": " + grade);
}

STEP 1 OF 9
    Ctrl + Enter to check

    Report Card V5 in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free