Skip to content
Java project #01Beginner

Student Result System

Turn raw marks into a ranked result sheet with totals, percentages, grades, pass/fail status, class statistics and subject toppers.

Estimated time
~3 hours to build
Files
4 files · 261 lines
Technologies
Java 21, java.util.Scanner, Records, Streams, String.format

Introduction

Every college publishes result sheets, and most of them are still built in spreadsheets by hand. This program does it from plain text: it validates each line, applies a per-subject pass mark, assigns grades, ranks the class with shared ranks for ties, and summarises how the class performed.

Problem statement

Read a line of subject names, then one line per student with a roll number, a name and one mark per subject. Reject lines with the wrong number of fields, non-numeric or out-of-range marks and duplicate roll numbers, giving the line number and reason. Print a ranked table with total, percentage, grade and PASS/FAIL (a student fails if any subject is below 35), then the number passed, the pass rate, the class average and the topper(s) in each subject.

Objectives

  • Model a student as a record with behaviour (total, percentage, grade)
  • Validate input line by line with exceptions
  • Sort with a Comparator chain and compute competition ranks
  • Use streams to compute statistics

Features

  • Any number of subjects, named on the first line
  • Validation with clear rejection messages
  • Shared ranks for equal totals (1, 2, 2, 4)
  • Grades O, A+, A, B, C, D and F; per-subject pass mark
  • Pass rate, class average and subject toppers including ties

Concepts demonstrated

  • Records
  • Input validation
  • Comparator.comparingInt / thenComparingInt
  • Streams (filter, mapToDouble, max)
  • Formatted output

System architecture

Student is a record holding the roll number, name and an int array of marks; it computes its own total, percentage, pass status and grade. main reads the subject line, then parses each student line inside a try block: NumberFormatException and IllegalArgumentException (for range and duplicate errors) are caught and reported with the line number. After reading, the list is sorted by total descending then roll ascending, and printed with ranks that only change when the total changes. Statistics and toppers use streams over the list.

Folder structure

TextProject tree
student-result-system/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

118 lines
Javasrc/Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
* Student Result System — reads students and their marks, computes totals, percentages,
* grades and pass/fail status, and prints a ranked result sheet with class statistics.
*
* Input format:
* first line: the subject names separated by spaces
* each further line: roll number, name, then one mark per subject
*/
public class Main {
static final int PASS_MARK = 35; // per subject
record Student(int roll, String name, int[] marks) {
int total() {
int t = 0;
for (int m : marks) t += m;
return t;
}
double percentage() { return total() * 100.0 / (marks.length * 100); }
boolean passed() {
for (int m : marks) if (m < PASS_MARK) return false;
return true;
}
String grade() {
if (!passed()) return "F";
double p = percentage();
if (p >= 90) return "O";
if (p >= 80) return "A+";
if (p >= 70) return "A";
if (p >= 60) return "B";
if (p >= 50) return "C";
return "D";
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if (!in.hasNextLine()) {
System.out.println("No input.");
return;
}
String[] subjects = in.nextLine().trim().split("\\s+");
List<Student> students = new ArrayList<>();
int lineNo = 1;
while (in.hasNextLine()) {
String line = in.nextLine().trim();
lineNo++;
if (line.isEmpty()) continue;
String[] parts = line.split("\\s+");
if (parts.length != subjects.length + 2) {
System.out.println("Line " + lineNo + ": expected roll, name and " + subjects.length + " marks - skipped");
continue;
}
try {
int roll = Integer.parseInt(parts[0]);
int[] marks = new int[subjects.length];
for (int i = 0; i < marks.length; i++) {
marks[i] = Integer.parseInt(parts[i + 2]);
if (marks[i] < 0 || marks[i] > 100) throw new IllegalArgumentException("mark " + marks[i] + " is out of range");
}
final int r = roll;
if (students.stream().anyMatch(s -> s.roll() == r)) throw new IllegalArgumentException("duplicate roll number " + roll);
students.add(new Student(roll, parts[1], marks));
} catch (NumberFormatException e) {
System.out.println("Line " + lineNo + ": numbers expected - skipped");
} catch (IllegalArgumentException e) {
System.out.println("Line " + lineNo + ": " + e.getMessage() + " - skipped");
}
}
if (students.isEmpty()) {
System.out.println("No valid students.");
return;
}
// Rank by total (highest first); equal totals share a rank and are listed by roll number.
students.sort(Comparator.comparingInt(Student::total).reversed().thenComparingInt(Student::roll));
StringBuilder header = new StringBuilder(String.format("%-5s %-5s %-8s", "Rank", "Roll", "Name"));
for (String s : subjects) header.append(String.format(" %7s", s));
header.append(String.format(" %6s %7s %5s %6s", "Total", "Percent", "Grade", "Result"));
System.out.println();
System.out.println(header);
System.out.println("-".repeat(header.length()));
int rank = 0;
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
if (i == 0 || s.total() != students.get(i - 1).total()) rank = i + 1;
StringBuilder row = new StringBuilder(String.format("%-5d %-5d %-8s", rank, s.roll(), s.name()));
for (int m : s.marks()) row.append(String.format(" %7d", m));
row.append(String.format(" %6d %6.2f%% %5s %6s", s.total(), s.percentage(), s.grade(), s.passed() ? "PASS" : "FAIL"));
System.out.println(row);
}
long passed = students.stream().filter(Student::passed).count();
double average = students.stream().mapToDouble(Student::percentage).average().orElse(0);
System.out.printf("%nStudents: %d Passed: %d Failed: %d Pass rate: %.1f%%%n", students.size(), passed, students.size() - passed, passed * 100.0 / students.size());
System.out.printf("Class average: %.2f%%%n", average);
System.out.println("\nSubject toppers:");
for (int j = 0; j < subjects.length; j++) {
final int col = j;
int best = students.stream().mapToInt(s -> s.marks()[col]).max().getAsInt();
List<String> names = students.stream().filter(s -> s.marks()[col] == best).map(Student::name).toList();
System.out.printf(" %-8s %3d %s%n", subjects[j], best, String.join(", ", names));
}
}
}

What each file does

src/Main.java
The Student record with its grading rules, the validating reader, the ranked report and the statistics.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Line 7: mark 101 is out of range - skipped
Line 8: numbers expected - skipped
Line 9: duplicate roll number 101 - skipped
Line 10: expected roll, name and 3 marks - skipped
Rank Roll Name Maths Physics Java Total Percent Grade Result
------------------------------------------------------------------------
1 101 Asha 92 88 95 275 91.67% O PASS
2 103 Meera 85 91 78 254 84.67% A+ PASS
2 105 Priya 85 91 78 254 84.67% A+ PASS
4 102 Ravi 67 30 80 177 59.00% F FAIL
5 104 John 45 58 62 165 55.00% C PASS
Students: 5 Passed: 4 Failed: 1 Pass rate: 80.0%
Class average: 75.00%
Subject toppers:
Maths 92 Asha
Physics 91 Meera, Priya
Java 95 Asha
Input
Maths Physics Java
101 Asha 92 88 95
102 Ravi 67 30 80
103 Meera 85 91 78
104 John 45 58 62
105 Priya 85 91 78
106 Karan 101 70 60
107 Sam 72 seventy 70
101 Duplicate 50 50 50
108 Omar 55 61

Testing

  • Compile and run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Four lines are rejected: a mark of 101, the word 'seventy', a duplicate roll number and a line with only two marks.
  • Meera and Priya have equal totals, so both are ranked 2 and the next student is ranked 4.
  • Ravi scores 30 in Physics, so he fails even though his percentage is 59%.

Common errors

InputMismatchException or NumberFormatException crashes the program

Read whole lines and parse them inside try/catch, as the program does, instead of calling nextInt directly.

Percentages print as 91.0 instead of 91.67

Divide using doubles: total() * 100.0 / (marks.length * 100).

Possible improvements

  • Read subject-wise maximum marks instead of assuming 100
  • Export the result sheet as CSV
  • Add a grace-marks rule for students who miss a pass by 1–2 marks

Additional challenges

  1. 1Print each student's best and worst subject.
  2. 2Compute the median and standard deviation of percentages.
  3. 3Draw a text histogram of grades.

Built and tested it yourself? Mark it to update your dashboard.