These are the notes for Java episode 13, the first project of the course. We join everything from episodes 1-12 (variables, operators, Scanner input, if/else, loops, arrays, 2D arrays, java.util.Arrays, Strings, methods) into one real program: it reads a class's marks, rejects bad input, works out totals, percentages, grades, ranks, the class topper and subject averages, and prints a neat report card with printf. On the way you meet four ideas every real program needs: requirements, decomposition, validation and edge cases. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.
The problem: result day by hand
Mrs Iyer is the class teacher of 10-B. On result day she has a paper register: 40 students x 5 subjects = 200 marks. For every student she adds the marks, works out the percentage, gives a grade; then ranks, the class topper and each subject's average. With a calculator, that's a midnight job, and one wrong key means redoing a page. Boring, careful, repeated work: exactly what computers are for.
The obvious program, and why it fails
One student, five variables:
public class Main {
public static void main(String[] args) {
int m1 = 87, m2 = 92, m3 = 78, m4 = 65, m5 = 90;
int total = m1 + m2 + m3 + m4 + m5;
double avg = total / 5;
System.out.println("Total: " + total);
System.out.println("Average: " + avg);
}
}
Total: 412
Average: 82.0
412 / 5 is 82.4, not 82.0. total is an int and 5 is an int, so Java does integer division (episode 3) and drops the decimals before the result is stored in the double. Fix: divide by 5.0.
double avg = total / 5.0; // Average: 82.4
Lesson 1 of every project: check at least one answer by hand.
Now scale to 40 students: m1 ... m200, and forty copies of the total line. One copy-paste slip like m181 + m182 + m183 + m183 + m185 (m183 twice, m184 missing) compiles and runs and gives a wrong total that nobody notices. One giant main is impossible to read, check or fix. The problem is not Java, it's the plan.
Plan first: requirements and decomposition
Requirements are the list of what the program must do, written in plain words before any code (like the measurements a tailor takes before cutting). Mrs Iyer's requirements:
- Read every student's name and marks (any number of students).
- Reject marks that are not between 0 and 100.
- Total and percentage for every student.
- A grade: A (90+), B (75+), C (60+), D (40+), F (below 40).
- A rank (1 = highest total).
- The class topper.
- The average of each subject.
- A neat report card with columns that line up.
Decomposition means splitting a big job into small, named jobs. Real-life example: a big wedding.
| A big wedding | Our program |
|---|---|
| the planner's checklist calls each specialist in order | main() calls each method in order |
| the caterer only does food | total(), percent() only do the maths |
| the photographer only takes photos | the printf report only prints |
| bad food? call the caterer, not the whole family | a wrong grade? fix grade() only |
Our tool for decomposition is the method (episode 11): one method per job, each small enough to test on its own.
The register is a 2D array
| Mrs Iyer's register | In Java |
|---|---|
| one row per student | marks[i]: row i = student i |
| one column per subject | marks[i][s]: student i's mark in subject s |
| names in the first column | String[] names: names[i] goes with row i |
Names can't live in an int array, so they get their own array. Two (later three) arrays that must stay in step: these are called parallel arrays, and they will cause trouble.
Reading the register with Scanner
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[][] readMarks(Scanner sc, String[] names) {
int[][] marks = new int[names.length][3];
for (int i = 0; i < names.length; i++) {
names[i] = sc.next();
for (int j = 0; j < 3; j++) {
marks[i][j] = sc.nextInt();
}
}
return marks;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] names = new String[n];
int[][] marks = readMarks(sc, names);
System.out.println(Arrays.toString(names));
System.out.println(Arrays.deepToString(marks));
}
}
Input:
4
Aarav 78 85 92
Diya 95 88 91
Kabir 45 38 52
Meera 88 94 79
Output:
[Aarav, Diya, Kabir, Meera]
[[78, 85, 92], [95, 88, 91], [45, 38, 52], [88, 94, 79]]
sc.next() reads one word (the name), sc.nextInt() one number. readMarks fills the names array that main passed in: Java passes the reference to the array by value (episode 11), so the method and main share the same array. It returns the new 2D array.
Total, percentage and grade
public class Main {
static int total(int[] row) {
int sum = 0;
for (int m : row) sum += m;
return sum;
}
static double percent(int[] row) {
return total(row) * 100.0 / (row.length * 100);
}
static char grade(double p) {
if (p >= 90) return 'A';
else if (p >= 75) return 'B';
else if (p >= 60) return 'C';
else if (p >= 40) return 'D';
return 'F';
}
public static void main(String[] args) {
int[] diya = {95, 88, 91};
double p = percent(diya);
System.out.println(total(diya) + " " + p
+ " " + grade(p));
}
}
274 91.33333333333333 A
totaluses the for-each loop to add up one row.percentmultiplies by100.0(adouble), so there's no integer division. The maximum isrow.length * 100.percentcallstotal: methods can use each other.
Without the last return 'F'; the compiler refuses:
Main.java:17: error: missing return statement
}
^
1 error
A method that promises to return a char must return one on every path. If the percentage is below 40, none of the ifs match, so the method would end with nothing.
Validation: a guard at the door
Mrs Iyer means 52 for Kabir and types 520. Without a check, Kabir's total becomes 603 out of 300 and he "tops" the class: garbage in, garbage out. Validation means checking that input makes sense before using it, like an airport security check.
import java.util.Scanner;
public class Main {
static int readMark(Scanner sc) {
int m = sc.nextInt();
while (m < 0 || m > 100) {
System.out.println("Invalid! Enter 0-100:");
m = sc.nextInt();
}
return m;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = readMark(sc);
System.out.println("Saved: " + m);
}
}
Input 105, -5, 88:
Invalid! Enter 0-100:
Invalid! Enter 0-100:
Saved: 88
"Ask again until it's right" is exactly a while loop. Edge cases are unusual inputs at or just past the limits, the ones most likely to break a program. For marks, always test 0, 100, -1 and 101.
The guard checks the range, not the type. Type the word eighty and nextInt crashes:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at Main.readMark(Main.java:5)
at Main.main(Main.java:15)
Handling crashes like this is exception handling (try/catch), episode 26.
The class topper
public class Main {
static int topper(int[] totals) {
int best = 0;
for (int i = 1; i < totals.length; i++) {
if (totals[i] > totals[best]) best = i;
}
return best;
}
public static void main(String[] args) {
String[] names = {"Aarav", "Diya", "Kabir", "Meera"};
int[] totals = {255, 274, 135, 261};
int t = topper(totals);
System.out.println("Topper: " + names[t] + " "
+ totals[t]);
}
}
Topper: Diya 274
Return the index, not the total: with the index you get both the name and the total. Edge case: with a tie, > keeps the first student; use >= to keep the last.
Subject averages: down a column
public class Main {
static double subjectAvg(int[][] marks, int s) {
int sum = 0;
for (int i = 0; i < marks.length; i++) {
sum += marks[i][s];
}
return (double) sum / marks.length;
}
public static void main(String[] args) {
int[][] marks = {{78, 85, 92}, {95, 88, 91},
{45, 38, 52}, {88, 94, 79}};
String[] subjects = {"Maths", "Science", "English"};
for (int s = 0; s < subjects.length; s++) {
System.out.println(subjects[s] + ": "
+ subjectAvg(marks, s));
}
}
}
Maths: 76.5
Science: 76.25
English: 78.5
A row total walks marks[i][0..]; a column average walks marks[0..][s]. With i <= marks.length the loop goes one row too far:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at Main.subjectAvg(Main.java:5)
at Main.main(Main.java:16)
Four rows are indexes 0 to 3. Use <.
Ranks: why Arrays.sort is the wrong tool
The obvious idea: sort the totals.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"Aarav", "Diya", "Kabir", "Meera"};
int[] totals = {255, 274, 135, 261};
Arrays.sort(totals);
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + " " + totals[i]);
}
}
}
Aarav 135
Diya 255
Kabir 261
Meera 274
Wrong pairs! 135 is Kabir's total, not Aarav's. Sorting one parallel array is like cutting the total column out of the register with scissors and rearranging only that strip: the names don't move.
The fix needs no sorting: your rank is 1 + the number of students who scored more than you.
public class Main {
static int rank(int[] totals, int i) {
int r = 1;
for (int t : totals) {
if (t > totals[i]) r++;
}
return r;
}
public static void main(String[] args) {
String[] names = {"Aarav", "Diya", "Kabir", "Meera"};
int[] totals = {255, 274, 135, 261};
for (int i = 0; i < names.length; i++) {
System.out.println("#" + rank(totals, i) + " "
+ names[i] + " " + totals[i]);
}
}
}
#3 Aarav 255
#1 Diya 274
#4 Kabir 135
#2 Meera 261
Ties share a rank, like a real result sheet. With totals {255, 274, 255, 261} the output is 255 #3, 274 #1, 255 #3, 261 #2.
printf: a printed form with boxes
println prints 91.33333333333333. A marksheet needs 91.33 and columns that line up. System.out.printf(template, values...) fills a template, like a printed form with boxes. Each blank is a format specifier:
| Specifier | Means | Example output |
|---|---|---|
%s |
a String | Diya |
%-6s |
a String, 6 wide, left-aligned | Diya |
%d |
a whole number (int, long) |
274 |
%5d |
a whole number, 5 wide, right-aligned | 274 |
%.2f |
a decimal, 2 places (rounded) | 91.33 |
%6.2f |
a decimal, 6 wide, 2 places | 91.33 |
%c |
a char |
A |
%n |
a new line | |
%% |
a real % sign |
% |
public class Main {
public static void main(String[] args) {
String row = "%-6s %5d %6.2f%%%n";
System.out.printf("%-6s %5s %7s%n",
"Name", "Total", "Percent");
System.out.printf(row, "Diya", 274, 91.3333);
System.out.printf(row, "Kabir", 135, 45.0);
}
}
Name Total Percent
Diya 274 91.33%
Kabir 135 45.00%
printf does not add a new line by itself: end the template with %n. String.format(...) takes the same template and returns the text as a String instead of printing it.
The complete program
import java.util.Scanner;
public class Main {
static int readMark(Scanner sc) {
int m = sc.nextInt();
while (m < 0 || m > 100) {
System.out.println("Invalid! Enter 0-100:");
m = sc.nextInt();
}
return m;
}
static int total(int[] row) {
int sum = 0;
for (int m : row) sum += m;
return sum;
}
static double percent(int[] row) {
return total(row) * 100.0 / (row.length * 100);
}
static char grade(double p) {
if (p >= 90) return 'A';
else if (p >= 75) return 'B';
else if (p >= 60) return 'C';
else if (p >= 40) return 'D';
return 'F';
}
static int rank(int[] totals, int i) {
int r = 1;
for (int t : totals) {
if (t > totals[i]) r++;
}
return r;
}
static int topper(int[] totals) {
int best = 0;
for (int i = 1; i < totals.length; i++) {
if (totals[i] > totals[best]) best = i;
}
return best;
}
static double subjectAvg(int[][] marks, int s) {
int sum = 0;
for (int i = 0; i < marks.length; i++) {
sum += marks[i][s];
}
return (double) sum / marks.length;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] subjects = {"Maths", "Science", "English"};
int n = sc.nextInt();
String[] names = new String[n];
int[][] marks = new int[n][subjects.length];
int[] totals = new int[n];
for (int i = 0; i < n; i++) {
names[i] = sc.next();
for (int s = 0; s < subjects.length; s++) {
marks[i][s] = readMark(sc);
}
totals[i] = total(marks[i]);
}
System.out.println("--- Class 10-B Results ---");
for (int i = 0; i < n; i++) {
double p = percent(marks[i]);
int r = rank(totals, i);
System.out.printf("#%d %-6s %4d %6.2f%% %c%n",
r, names[i], totals[i], p, grade(p));
}
int t = topper(totals);
System.out.println("Topper: " + names[t]);
for (int s = 0; s < subjects.length; s++) {
System.out.printf("%-8s avg %.2f%n",
subjects[s], subjectAvg(marks, s));
}
}
}
Input (Kabir's typo 520, then the correct 52 on the next line):
4
Aarav 78 85 92
Diya 95 88 91
Kabir 45 38 520
52
Meera 88 94 79
Output:
Invalid! Enter 0-100:
--- Class 10-B Results ---
#3 Aarav 255 85.00% B
#1 Diya 274 91.33% A
#4 Kabir 135 45.00% D
#2 Meera 261 87.00% B
Topper: Diya
Maths avg 76.50
Science avg 76.25
English avg 78.50
main reads like the planner's checklist. For 40 students and 5 subjects, add two names to subjects and type more input lines: no method changes.
How a professional builds a program (what you just did)
- Requirements: what must it do?
- Decompose into small jobs (methods).
- Build and test one method at a time, with a tiny
main. - Assemble them in
main. - Check one answer by hand; test the edge cases.
Common mistakes (and the real error messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
double avg = total / 5; |
no error, 82.0 instead of 82.4 |
int / int drops the decimals |
total / 5.0 |
if ... else if ... with no final return |
error: missing return statement |
some path returns nothing | add return 'F'; |
typing eighty for sc.nextInt() |
Exception in thread "main" java.util.InputMismatchException |
nextInt needs digits |
type numbers (exception handling: episode 26) |
for (int i = 0; i <= marks.length; i++) |
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 |
rows go 0 to length - 1 |
i < marks.length |
Arrays.sort(totals) for ranks |
no error, totals under the wrong names | only one parallel array moved | rank = 1 + how many scored more |
printf("%d", 91.5) |
java.util.IllegalFormatConversionException: d != java.lang.Double |
%d is for whole numbers |
%.1f for decimals |
printf without %n |
the next print continues on the same line | printf adds no new line |
end with %n |
Extension ideas
- 5 subjects and 40 students (change
subjects, give more input). - PASS/FAIL: any subject below 33 fails.
- The topper of each subject.
- The class list in rank order.
- A histogram of grades:
A: ***,B: ****using acharcount array. - Save the report into a
StringBuilder(episode 10) and print it once.
Practice
- Rewrite
gradewith aswitchon(int) p / 10: 90+ A, 70+ B, 60+ C, 40+ D, else F. - Write
boolean passed(int[] row): false if any mark is below 33. - Write
int subjectTopper(int[][] marks, int s). - Print the class in rank order, rank 1 first, without
Arrays.sort. - What does
rankreturn for every student if all four totals are equal?
Solutions
2-4 together (tested; Kabir's Science mark changed to 28 so someone fails):
public class Main {
static boolean passed(int[] row) {
for (int m : row) {
if (m < 33) return false;
}
return true;
}
static int subjectTopper(int[][] marks, int s) {
int best = 0;
for (int i = 1; i < marks.length; i++) {
if (marks[i][s] > marks[best][s]) best = i;
}
return best;
}
public static void main(String[] args) {
String[] names = {"Aarav", "Diya", "Kabir", "Meera"};
String[] subjects = {"Maths", "Science", "English"};
int[][] marks = {{78, 85, 92}, {95, 88, 91}, {45, 28, 52}, {88, 94, 79}};
int[] totals = {255, 274, 125, 261};
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + (passed(marks[i]) ? "PASS" : "FAIL"));
}
for (int s = 0; s < subjects.length; s++) {
int b = subjectTopper(marks, s);
System.out.println(subjects[s] + " topper: " + names[b] + " (" + marks[b][s] + ")");
}
// rank order: print rank 1, then 2, ...
for (int r = 1; r <= names.length; r++) {
for (int i = 0; i < names.length; i++) {
int rank = 1;
for (int t : totals) if (t > totals[i]) rank++;
if (rank == r) System.out.println("#" + r + " " + names[i] + " " + totals[i]);
}
}
}
}
Aarav: PASS
Diya: PASS
Kabir: FAIL
Meera: PASS
Maths topper: Diya (95)
Science topper: Meera (94)
English topper: Aarav (92)
#1 Diya 274
#2 Meera 261
#3 Aarav 255
#4 Kabir 125
-
java static String grade(double p) { switch ((int) p / 10) { case 10: case 9: return "A"; case 8: case 7: return "B"; case 6: return "C"; case 5: case 4: return "D"; default: return "F"; } }((int) p / 10casts first, then integer-divides: 91.33 → 91 → 9.) -
1for everyone: nobody scored more than anyone else, so all share rank 1.
Quick quiz
What does this print?
int[] totals = {250, 270, 250, 260};
int r = 1;
for (int t : totals) {
if (t > totals[2]) r++;
}
System.out.println(r);
- A.
1 - B.
2 - C.
3 - D.
4
Answer
C. 3. totals[2] is 250. Two totals are greater (270 and 260), so r = 1 + 2 = 3. The other 250 is a tie, and 250 > 250 is false, so both 250s share rank 3.
Interview questions
- Why does
int total = 412; double avg = total / 5;give 82.0? Both operands areint, so integer division happens first; the result is only widened todoubleafterwards. Use5.0or cast:(double) total / 5. - What is input validation and why does it matter? Checking input is sensible before using it; otherwise wrong data silently produces wrong results (garbage in, garbage out).
- What are edge cases? Give examples for a marks program. Inputs at or just past the limits: 0, 100, -1, 101, zero students, ties.
- What are parallel arrays, and what's their weakness? Several arrays where index
idescribes the same thing; they must be kept in step manually (sorting one breaks the link). Classes fix this (episode 14). - How do you rank without sorting? Rank = 1 + count of strictly greater values; O(n²) but simple, and ties share a rank.
printlnvsprintfvsString.format?printlnprints and adds a new line;printfprints a formatted template with no automatic new line;String.formatreturns the formatted String.- Why split a program into small methods? Each is readable, testable on its own, reusable, and a bug is fixed in one place.
Glossary
| Term | Meaning | Example |
|---|---|---|
| project | a complete program that solves a real problem | the marks system |
| requirements | what the program must do, in plain words, written before coding | "reject marks outside 0-100" |
| decomposition | splitting a big job into small, named jobs (methods) | total, grade, rank |
| method | a named block of steps you can call (episode 11) | total(row) |
| 2D array | an array of arrays: rows and columns | int[][] marks |
| row / column | marks[i] is a row; marks[*][s] is a column |
student / subject |
| parallel arrays | separate arrays where index i means the same thing |
names[i], totals[i] |
| integer division | int / int drops the decimals |
412 / 5 is 82 |
| validation | checking input makes sense before using it | while (m < 0 \|\| m > 100) |
| edge case | an unusual input at or past the limits | 0, 100, -1, 101 |
| garbage in, garbage out | wrong input gives wrong output | Kabir 603/300 |
| exception | an error that stops the program while it runs | InputMismatchException |
sc.next() |
reads one word | a name |
sc.nextInt() |
reads one whole number | a mark |
| topper | the student with the highest total | Diya |
| rank | position by total; 1 is the highest | 1 + how many scored more |
| tie | two equal values | two 250s |
printf |
prints a template filled with values | printf("%5d", 274) |
| format specifier | a blank in the template, starting with % |
%-6s, %.2f |
%n |
a new line inside a printf template |
|
String.format |
like printf, but returns the String |
String.format("%.2f", p) |
Summary
- Plan first: write the requirements, then decompose the job into small methods;
mainis the checklist. - The register is a 2D array
int[][] marksplus a parallelString[] names. total,percent(divide with100.0),grade(every path mustreturn).- Validate input with a
whileloop and test the edge cases 0, 100, -1, 101. - Topper by index; subject averages walk down a column (
i < marks.length). Arrays.sorton one parallel array scrambles the pairs; rank = 1 + how many scored more.printfwith%-6s,%5d,%.2f,%c,%n,%%for a neat report card.
Next episode: Classes and objects. One student is spread over three arrays (names[i], marks[i], totals[i]). Next we invent a single thing that holds a student's name, marks and total together, and see where it lives: the stack and the heap.