Grading Case Study in Java

By Nicholas Duchon, April 22, 2014

From Venit, Section 6.8, pp 332-342, in Java

import java.util.Scanner;

public class Grading {
    static Scanner stin = new Scanner (System.in);
   
    public static void main (String args []) {
        int m = 50;
        int used = 0;
        String [] names  = new String [m];
        int    [] ids    = new int    [m];
        double [] scores = new double [m];
        char   [] grades = new char   [m];
        used = initArrays (names, ids, scores, grades);
        printAll (names, ids, scores, grades, used);
        double av = getAverage (scores, used);
        System.out.println ("Average is: " + av);
        System.out.println ("End");
    } // end main
   
    static double getAverage (double [] sc, int used) {
        double sum = 0;
        for (int i = 0; i < used; i++)
            sum = sum + sc[i];
        return sum / used;
    } // end getAverage
   
    static int initArrays (String [] n, int [] id, double [] sc, char [] g) {
        int cnt = 0;
        for (int i = 0; i < n.length; i++) {
            System.out.print("Enter name, id, score: ");
            n  [i] = stin.next();
            if (n[i].equals("**")) break;
            cnt ++;
            id [i] = stin.nextInt();
            sc [i] = stin.nextDouble ();
            g  [i] = getGrade (sc[i]);
        } // end input for loop
        return cnt;
    } // end initArrays
   
    static char getGrade (double score) {
        if (score >= 90) return 'A';
        if (score >= 80) return 'B';
        if (score >= 70) return 'C';
        if (score >= 55) return 'D';
        return 'F';
    } // end getGrade
   
    static void printAll (String [] n, int [] id, double [] sc, char [] g, int cnt) {
        System.out.printf("%-20s%10s%6s  %s\n", "Student Name", "ID Number", "Score", "Grade");
        for (int i = 0; i < cnt; i++) {
            System.out.printf("%-20s%10d%6.1f     %c\n", n[i], id[i], sc[i], g[i]);
        } // end for each active element
    } // end printAll

} // end Grading

Output:

Enter name, id, score: s 3 4
Enter name, id, score: **
Student Name         ID Number Score  Grade
s                            3   4.0     F
Average is: 4.0
End