Skip to content
Tutorials Center
My learning

Topics

Lesson 173 of 201 ยท Projects

Project: Grade Book

Build a Java grade book step by step. Read scores from input, validate them, compute weighted averages and letter grades, and print a neat class report.

Reading about arrays, loops and methods is one thing. Combining them into a program that takes messy real-world input and produces something useful is another, and it's where most of the learning happens. In this project you'll build a grade book: a program that reads a class's scores, works out each student's average and letter grade, and prints a report a teacher could actually hand out.

You'll build it in five stages. Every stage is a complete, runnable program that contains everything written so far, so you can run any stage on its own, change the input in the Input box, and see what happens. Along the way you'll make the decisions a real program needs: what the input looks like, what happens when a line is wrong, how to round, and how to lay out a table that stays readable.

The project practices arrays, 2D arrays, methods, reading input, string methods and formatted output with printf. If one of those feels shaky, keep its lesson open in another tab.

What we're building

At the end, you'll paste lines like these into the Input box:

TEXT
Quiz1:15 Quiz2:15 Midterm:30 Final:40
Ana 88 92 79 85
Bilal 72 65 80 70
Chen 95 98 91 99

The first line names the assignments and gives each a weight (a percentage of the final grade). Every other line is a student name followed by one score per assignment. The program will print a table with every score, each student's weighted average and letter grade, the class average for each assignment, the best and weakest student, and a small chart of how many students got each letter.

Before writing code, it's worth fixing the rules, because they decide the code:

  • Scores are whole numbers from 0 to 100.
  • Names are a single word (we'll discuss lifting that limit at the end).
  • Fields are separated by one or more spaces, so sloppy spacing is fine.
  • A broken student line is reported and skipped; it must not stop the whole report.
  • Letter grades use the common scale: 90 and above is an A, 80 a B, 70 a C, 60 a D, anything lower an F.

Stage 1: one student

Start with the smallest version that does something real: read one line, split it into a name and scores, and compute the average.

Java Stage 1: average for one student

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few details here are worth slowing down for, because they come back in every stage:

  • line.trim().split("\\s+") splits on runs of whitespace. With a plain split(" "), two spaces between fields would produce an empty string, and Integer.parseInt("") would crash. trim() first removes leading and trailing spaces, which would otherwise produce an empty first element. The String Methods lesson covers split in detail.
  • The scores array is sized parts.length - 1 because the first part is the name. The loop index i walks through parts, and i - 1 is the matching position in scores. Off-by-one mistakes love this kind of code, so it pays to read it twice.
  • average casts to double before dividing. Without the cast, sum / scores.length would be integer division and 344 / 4 would give 86 even if the true average were 86.75.

Computing the average in its own method is the first design decision of the project. main reads and prints; average calculates. When we later need the average of a whole assignment column, or a weighted average, we'll add methods next to it instead of piling more code into main. Try adding a fifth score to the Input box: the program adapts, because nothing assumes there are exactly four.

Stage 2: the whole class

A class has many students, and a grade book needs all of them at once: you can't compute the class average for the midterm until you've read every midterm score. That means storing the data, and the natural shape is a 2D array: one row per student, one column per assignment.

There's a catch. An array's size is fixed when you create it, but we don't know how many students are in the input until we've read it all. The simple fix is to read every line into a List<String> first (a list grows as needed; see ArrayList), then create arrays of exactly the right size.

We also add a header line with assignment names, so the program knows how many scores each student should have and what to call them.

Java Stage 2: storing the class in a 2D array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how average didn't change at all. scores[r] is a row of the 2D array, and a row is just an int[], so the method from Stage 1 works on it directly. That's the payoff of writing small methods with clear inputs.

The program uses parallel arrays: names[r] and scores[r] describe the same student because they share the index r. It's the simplest structure that works with what we've learned so far. Its weakness is that nothing ties the two together: sort one array and forget the other, and every name gets someone else's scores. In a bigger program you'd group a name and its scores in one object, like a record; the other projects in this chapter do exactly that.

while (in.hasNextLine()) is the standard "read until the input ends" loop from Reading User Input. Blank lines are skipped so an accidental empty line at the end of the Input box doesn't become a student with no name.

Stage 3: validation and letter grades

Real input is messy. Teachers mistype, copy-paste adds stray text, a score of 110 slips in. Try changing a score in Stage 2 to eighty and pressing Run: the whole program dies with a NumberFormatException and prints nothing useful. A grade book that refuses to work because of one typo is worse than useless.

So this stage adds two things: validation, which reports and skips bad lines, and letter grades.

Java Stage 3: skipping bad lines and adding letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output starts with three warnings, one for each broken line, and then grades for the five good students. Here's how the pieces fit:

One method decides what "valid" means. parseScores checks the number of scores, that each one is a number, and that it's in range. Whenever something is wrong it throws an IllegalArgumentException with a message written for a human. The caller catches it, prints the line number and the message, and moves on. This split matters: parseScores doesn't know or care how problems are reported, and main doesn't need to know which rules exist. Add a new rule later and only one method changes.

Exceptions are translated, not leaked. Integer.parseInt throws a NumberFormatException whose message is For input string: "eighty": accurate, but written for programmers. We catch it and throw our own clearer message. As it happens, NumberFormatException is a subclass of IllegalArgumentException, so the outer catch would have caught it anyway; translating it is about the message, not about catching. The Exceptions lesson covers catching, and Exception Handling Best Practices explains why you translate low-level errors at boundaries like this.

Line numbers are counted from the raw input. Blank lines are now kept in rows and skipped inside the loop, so the index r always matches the original line (r + 2, because lines are numbered from 1 and the header is line 1). A message that says "line 4" when the problem is on line 5 sends people looking in the wrong place.

Arrays are trimmed at the end. We create the arrays with room for every line, fill them only with valid students (count tracks how many), and shrink them with Arrays.copyOf. Afterward names.length is the real number of students, and no later code has to remember to stop at count. scores is created as new int[rows.size()][], a jagged array with no rows yet, because each row comes from parseScores.

Rounding happens before grading. letterGrade uses a switch expression on the tens digit: (int) 86.8 / 10 is 8, a B. But which number do you grade? Imagine an average of 89.96. Printed with one decimal it shows as 90.0, yet (int) 89.96 / 10 is 8, so the student would see "90.0 B" on the report and rightly complain. The rule that avoids this is simple: round first, then grade and display the same rounded value. That's what roundToTenth is for. It's a small decision, but this exact inconsistency has caused real grading disputes.

Note the cast: (int) average / 10 casts first and then divides as integers. A cast binds more tightly than division, as the precedence lesson shows.

Stage 4: weighted averages

In most courses the final exam counts for more than a quiz. Our header line now gives each assignment a weight after a colon, such as Final:40, and the weights must add up to 100. A student's grade becomes the weighted average: multiply each score by its weight, add those products, and divide by the total weight.

Java Stage 4: weighted averages from the header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compare the plain and weighted numbers. Ana's strong quizzes count for less now, so her average drops from 86.0 to 84.7; Emeka did best on the heavily weighted final, so his rises from 83.3 to 85.2. Weighting changes real outcomes, which is why the program checks the weights before doing anything else.

Some design notes:

  • Fail early on a broken header. A bad student line affects one student, so we skip it. A bad header affects everyone: if the weights add up to 90, every grade is wrong. So instead of guessing, the program stops with a clear message and a return from main. Try changing Final:40 to Final:30 to see it. A missing weight (Final with no colon) counts as 0, which the sum check then catches.
  • A tiny sum method removed duplication. average, weightedAverage and the weight check all need a sum, so it became its own method, and average shrank to one line. Spotting repeated code and giving it a name is a habit worth building.
  • The weighted sum stays an int until the final division. Scores and weights are whole numbers, so their products are exact, and we convert to double only once. Mixing double in early wouldn't be wrong here, but keeping exact values as long as possible is a good default with numbers.
  • The weights array is parallel to the assignments array, just like names and scores. weights[i] belongs to assignments[i] and to column i of scores.

Stage 5: the class report

The numbers are right; now make them readable. A report is a table, and tables need aligned columns. That's the job of printf with width specifiers: %-8s prints a string left-aligned in 8 characters, %7d prints an integer right-aligned in 7, and %7.1f prints a number with one decimal in 7 characters. The Formatting Strings lesson lists every option.

This final stage also adds class statistics: the average for each assignment (a column of the 2D array), the overall class average, the top and weakest student, and a grade distribution.

Java Stage 5: the complete grade book

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

That's the finished grade book. Run it, then experiment: add a student, change a weight, break a line on purpose. Here's what's new in this stage and why it's built this way.

Computing first, printing second

main now computes every student's final result into a double[] finals array before printing anything. The report needs those results several times: in the table, for the class average, for the top and weakest student and for the distribution. Computing them once and storing them avoids repeating the same calculation (and the risk that two copies drift apart when someone edits one).

Printing lives in its own method, printReport. Its long parameter list is a sign of the parallel-array design reaching its limits; with a Student record or a GradeBook class you'd pass one object instead. That's fine for this project, and it's a good illustration of why those tools exist.

Lining up the columns

Every column has a fixed width, and every row uses the same widths: %-10s for names, %8d for scores, %9.1f for the average. That's the whole secret of an aligned table. The header uses %8s for the assignment names so they sit right above their right-aligned numbers.

Two small tricks appear in the weight row. %7d%% prints the weight in 7 characters followed by a literal percent sign, because %% is how printf writes %. And System.out.println() with no argument just ends the line. The separator rule is built with "-".repeat(...) from the same widths the columns use, so it stays the right length if you add assignments.

Notice %n instead of \n at the end of printf formats. %n writes the platform's line separator; on our server both look the same, but %n is the convention in printf strings.

Column averages and overloading

columnAverage(scores, a) walks down column a of the 2D array: for every row it takes row[column]. Rows are the outer index and columns the inner one, so a column has to be gathered row by row, as covered in Multidimensional Arrays.

There are now two methods called average: one takes int[], the other double[]. That's method overloading. Java picks the right one from the argument type, so average(finals) calls the double[] version. The class average is the average of the students' final results, which is what a teacher usually means.

Finding the best and worst

indexOfMax and indexOfMin return an index, not a value. That's deliberate: with parallel arrays, the index is what links a result to a name, so returning 92.5 alone would lose the information of who scored it. If two students tie, the first one wins, because the comparison is a strict >.

The distribution chart

The distribution uses a neat trick: letters.indexOf(letterGrade(result)) turns a letter into an array index (A is 0, B is 1 and so on), so one line counts every result. The bar is "#".repeat(counts[i]), padded with %-10s so the numbers after it stay lined up.

Guarding against an empty class

If every student line is broken, names.length is 0. Without the check in main, average(finals) would divide 0.0 by 0 and print NaN, and indexOfMax would crash reading values[0]. Thinking about the empty case is one of the habits that separates programs that work in a demo from programs that work for users. Try it: delete every student line and run.

When you build your own projects, copy this rhythm: get one tiny case working, then grow it one feature at a time, running after every change. Each stage here was runnable on its own, so a mistake could only come from the last few lines you added.

Ideas to extend it

You have a solid base. These extensions each practice something specific; try them in the last editor:

  • Names with spaces. Allow lines like Maria Lopez 80 75 90 88 by treating the last N fields as scores and joining everything before them into the name with String.join(" ", ...) and Arrays.copyOfRange.
  • Plus and minus grades. Return B+ for 87โ€“89.9 and B- for 80โ€“82.9. Use the ones digit of the rounded average.
  • Sort the table by final result, highest first. With parallel arrays you must swap entries in names, scores and finals together, which is a good argument for the next idea.
  • Use a record. Replace the parallel arrays with record Student(String name, int[] scores, double result) and a Student[] or List<Student>. Watch how much simpler printReport's parameter list and the sorting become. See Records.
  • Drop the lowest quiz. Many teachers ignore each student's worst quiz. Decide how that interacts with weights, then implement it.
  • Missing work. Accept - for a missing score and count it as 0, but mark it with a * in the table.
  • Median and standard deviation for each assignment, using Arrays.sort on a copy of the column and Math.sqrt.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Stage 1, what would " Ana 88 92".split(" ") produce compared to .trim().split("\\s+")?

    Splitting on a single space turns each extra space into an empty element. trim plus the \s+ pattern removes the edges and treats any run of whitespace as one separator.
  2. 2. A student's exact weighted average is 89.96. The program rounds to one decimal and then grades. What does the report show?

    roundToTenth turns 89.96 into 90.0, and letterGrade receives that same 90.0, so the student gets an A. Grading the unrounded value would print 90.0 next to a B.
  3. 3. Why does Stage 2 read all lines into a List before creating the arrays?

    The list grows while reading; once its size is known, arrays of exactly that size can be created.
  4. 4. What does System.out.printf(\"%7d%%\", 15) print?

    %7d right-aligns 15 in seven characters (five spaces, then 15) and %% prints a single percent sign.
  5. 5. Why do indexOfMax and indexOfMin return an index instead of the highest or lowest value?

    With parallel arrays, the shared index is the only connection between a name and its numbers, so the report needs the index to print who scored the result.

Summary

  • The grade book reads a weighted header and one line per student, validates every line, computes weighted averages and letter grades, and prints an aligned report with class statistics.
  • trim().split("\\s+") tolerates messy spacing; reading lines into a List first lets you size arrays exactly.
  • Validation lives in one method that throws IllegalArgumentException with human-friendly messages; the caller reports the line number and skips the line, while a broken header stops the program.
  • Round first, then grade and display the same value, so the report never contradicts itself.
  • printf widths (%-10s, %8d, %9.1f) align tables; %% prints a percent sign and %n ends a line.
  • Parallel arrays work but strain as programs grow; records and classes are the next step, as the following projects show.

Next: Project: Bank Account System, where you'll model accounts with classes, inheritance and custom exceptions.