Start learning free

LESSON 200 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Report Card V4 in Java: Grading Many Students with a Loop

Practice Read the full explanation

Combine lists, loops, and conditionals to print a letter grade for each student in a class.

You start with:

String[] names = {"Alice", "Bob", "Carol", "Dan"};
int[] scores = {92, 78, 85, 67};

Build:

Alice: A
Bob: C
Carol: B
Dan: D

Rules:

  • Loop over the indices of the students (names.length) so you can read the name and the score at the same position.
  • Use the same scale as V3: 90+ A, 80-89 B, 70-79 C, 60-69 D, below 60 F.
  • On each iteration print the name, a colon and a space, then the grade, for example Alice: A.

Use Java arrays and for (int i = 0; i < names.length; i++).

String[] names = {"Alice", "Bob", "Carol", "Dan"};
int[] scores = {92, 78, 85, 67};

for (int i = 0; i < names.length; i++) {
    int score = scores[i];
    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(names[i] + ": " + grade);
}

STEP 1 OF 9
    Ctrl + Enter to check

    JAVA · PROJECTS: EVERYDAY PROGRAMS

    Report Card V4 in Java, explained

    Problem overview

    Version 4 grades a whole class. Two parallel arrays describe it: names holds the students' names and scores holds their scores, and the same position in both arrays belongs to the same student. For each student the program prints the name, a colon, a space and the letter grade.

    The grading scale is the one from version 3: 90 or more is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and below 60 is F. For the starting data the output is four lines:

    Alice: A
    Bob: C
    Carol: B
    Dan: D
    

    Approach: one loop over positions, the ladder inside

    Version 3 already has the ladder that turns one score into one grade. What is new is doing it once per student. A for loop that counts positions does this: the counter i goes from 0 up to the last position, and at each pass names[i] and scores[i] are the matching pair.

    This is why the loop counts positions and doesn't use the enhanced for over just one array. With only for (int s : scores) the program would have the score but no way to find the name next to it. The index connects the two arrays.

    Everything that depends on one student, the score, the grade and the print, goes inside the loop body, so that it repeats for each student.

    Step by step

    1. Write the loop. for (int i = 0; i < names.length; i++) visits positions 0, 1, 2 and 3. Arrays have a length field, written without parentheses, and the condition i < names.length stops before the first position that doesn't exist. Close the loop's brace right away so the later lines go inside it.
    2. Read the score. Declare int score = scores[i]; inside the loop. The same i reads the score that belongs to the name at that position.
    3. Declare grade. String grade; goes inside the loop with no value, because the ladder will assign it.
    4. Start the ladder at the top. if (score >= 90) sets "A". Starting with the highest grade means each later test needs only a lower limit.
    5. Add the B branch with else if for 80 or more. This test runs only when the score is below 90.
    6. Add the C branch for 70 or more.
    7. Add the D branch for 60 or more.
    8. End with else. It sets "F", so grade has a value after every pass.
    9. Print inside the loop. After the ladder, print names[i], the text ": " and grade. Because the print is inside the loop, it runs once per student, which gives the four lines.

    The solution in Java

    String[] names = {"Alice", "Bob", "Carol", "Dan"};
    int[] scores = {92, 78, 85, 67};
    
    for (int i = 0; i < names.length; i++) {
        int score = scores[i];
        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(names[i] + ": " + grade);
    }
    

    Java details that matter here:

    • Variables inside the loop are new on every pass. score and grade are declared in the loop body, so each pass starts with fresh variables. That is why grade doesn't need a starting value and can't carry a stale grade from the previous student.
    • Two array types. String[] holds the names and int[] the scores. The braces in {"Alice", ...} are an array initializer that sets the length from the number of elements.
    • Printing with +. names[i] + ": " + grade joins three strings. The text ": " contains the colon and the space that the output format asks for.

    Complexity

    Time: O(n), where n is the number of students. The loop makes one pass, and the ladder does at most four comparisons per student, which is a constant amount of work.

    Space: O(1) beyond the input. The loop keeps a few variables, and the output is printed as it is produced, not collected.

    Edge cases and common mistakes

    • Off-by-one in the condition. Writing i <= names.length makes the loop run once too often. Reading a position that doesn't exist throws ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 on a four-element array.
    • Arrays of different lengths. The loop is driven by names.length. If scores has fewer elements than names, the program prints the students that have a score and then fails with ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3.
    • Printing outside the loop. A println after the closing brace runs once. It would also not compile there, since grade and score exist only inside the loop.
    • An empty class. With empty arrays the condition is false from the start, the body never runs and nothing is printed.
    • Boundary scores. A score of 90 is an A and 60 is a D, while 59 is an F. For the data 100, 90, 59, 60 and 0 the grades come out A, A, F, D and F.

    Testing

    Try these in the editor above, and compare the output with the table:

    Names and scoresOutput
    Alice 92, Bob 78, Carol 85, Dan 67A, C, B, D
    Eve 100, Finn 90, Gus 59, Hana 60, Ivy 0A, A, F, D, F
    no studentsno output
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free