// This program reads a file of students' attendance in section // (a 1 means a student attended, a 0 means they did not) and // uses arrays to compute attendance points and grade percentages. // // Each line of input represents one section and each 5 characters // on a line represent the 5 students in the section. // // This version has better decomposition into methods and reports // the results to an output file. import java.io.*; import java.util.*; public class Sections2 { public static final int STUDENTS = 5; // # of students/section public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); PrintStream stream = new PrintStream(new File("grades.txt")); int count = 1; while (input.hasNextLine()) { String line = input.nextLine(); // "111111101011111101001110110110110001110010100" int[] attended = section(line, count); int[] points = sectionPoints(attended); double[] grades = sectionPercentages(points); results(stream, count, attended, points, grades); count++; } } // This method processes a single section line from the file. public static int[] section(String line, int number) { int[] attended = new int[STUDENTS]; // [0, 0, 0, 0, 0] for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); // '1' or '0' // i 0 1 2 3 4 5 6 7 8 9 10 11 ... // student 0 1 2 3 4 0 1 2 3 4 0 1 ... // expression to connect them: i % 5 int student = i % STUDENTS; if (c == '1') { attended[student]++; } } // sectionGrades(attended); return attended; } // This method accepts the array for the number of sections attended // as a parameter and computes the students' section points. public static int[] sectionPoints(int[] attended) { // compute section points from # sections attended int[] points = new int[STUDENTS]; for (int i = 0; i < STUDENTS; i++) { points[i] = Math.min(20, attended[i] * 3); } return points; } // Computes the section grades from the points earned. public static double[] sectionPercentages(int[] points) { double[] grades = new double[STUDENTS]; for (int i = 0; i < STUDENTS; i++) { grades[i] = points[i] / 20.0 * 100; } return grades; } // Reports the results to the output file. public static void results(PrintStream stream, int number, int[] attended, int[] points, double[] grades) { stream.println("Section " + number + ":"); stream.println(Arrays.toString(attended)); stream.println(Arrays.toString(points)); stream.println(Arrays.toString(grades)); } }