import java.io.*; // for File import java.util.*; // for Scanner, Arrays /* * CSE 142 * Arrays For Tallying * Section Attendance * * This program calculates and prints the quiz section attendance * points and grades for each student in each quiz section. * * This version demonstrates printing to a file. */ public class SectionAttendance2 { public static void main(String[] args) throws FileNotFoundException { // get a scanner on the file, and loop through each line Scanner input = new Scanner(new File("section.txt")); // creates a new file if needed or overwrites an existing file PrintStream out = new PrintStream(new File("output.txt")); int section = 1; while (input.hasNextLine()) { String line = input.nextLine(); int[] totalPoints = getPoints(line); capPoints(totalPoints); double[] percents = getPercents(totalPoints); printStats(out, section, totalPoints, percents); // printStats(System.out, section, totalPoints, percents); section++; } } // Calculate each student's points within a given section. // Return an int[] with student 0's points at element 0, // student 1's points at element 1 etc. // Uses the cumulative sum pattern we discussed. public static int[] getPoints(String line) { // Make an array, where each element is the points for a student int[] totalPoints = new int[5]; // 5 students -> length 5 array // for each character in the string for (int i = 0; i < line.length(); i++) { char attendance = line.charAt(i); int points = 3; // assume student gets 3 points if (attendance == 'a') { points = 0; } else if (attendance == 'n') { points = 1; } // 0, 5, 10, 15... -> 0 // 1, 6, 11, 16... -> 1 // find correct student using mod by the number of students // add 0, 1, or 3 points to the correct student int curStudent = i % totalPoints.length; totalPoints[curStudent] += points; } return totalPoints; } // Cap the points for each student at 20. // Uses the min pattern we discussed. public static void capPoints(int[] points) { for (int i = 0; i < points.length; i++) { points[i] = Math.min(20, points[i]); } } // Calculate the percentage for each student out of a possible 20 points. public static double[] getPercents(int[] points) { double[] percents = new double[points.length]; for (int i = 0; i < points.length; i++) { percents[i] = points[i] * 100.0 / 20.0; } return percents; } // Print the stats for a section in the following format: // Section # // Student points: [#, #, #, #, #] // Student grades: [#.#, #.#, #.#, #.#, #.#] // Output goes to the given PrintStream public static void printStats(PrintStream out, int section, int[] totalPoints, double[] percents) { out.println("Section " + section); out.println("Student points: " + Arrays.toString(totalPoints)); out.println("Student grades: " + Arrays.toString(percents)); out.println(); } }