/* CSE 142, Autumn 2007, Marty Stepp This program reads an input file of data about students' attendance in section and outputs the attendance, points earned, and grade percentages for each student in each section. The format of the input file is explained in the Ch. 7 lecture slides. Example line of input from the file, sections.txt: 111111101011111101001110110110110001110010100 Example output for the above line: Sections attended: [9, 6, 7, 4, 3] Student scores: [20, 18, 20, 12, 9] Student grades: [100.0, 90.0, 100.0, 60.0, 45.0] This second version uses methods that pass arrays as parameters and returns them. It also sends its output to a file using a PrintStream object */ import java.io.*; // for File, PrintStream import java.util.*; // for Scanner public class Sections { // this global 'boolean flag' sends the output to System.out when false, // and to the file "sections_output.txt" when true public static final boolean USE_OUTPUT_FILE = true; public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); // decide which output source to use, based on the flag PrintStream out; if (USE_OUTPUT_FILE) { out = new PrintStream(new File("sections_output.txt")); } else { out = System.out; } while (input.hasNextLine()) { // process one section String line = input.nextLine(); int[] attended = countAttended(line); int[] points = computePoints(attended); double[] grades = computeGrades(points); outputResults(attended, points, grades, out); } } // Produces all output about a particular section. // The output is sent to the given print stream. public static void outputResults(int[] attended, int[] points, double[] grades, PrintStream out) { out.println("Sections attended: " + Arrays.toString(attended)); out.println("Sections scores: " + Arrays.toString(points)); out.println("Sections grades: " + Arrays.toString(grades)); out.println(); } // Counts the number of sections attended by each student for a particular section. // Returns the data as an array. public static int[] countAttended(String line) { int[] attended = new int[5]; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); // c == '1' or c == '0' if (c == '1') { // student attended their section attended[i % 5]++; } } return attended; } // Computes the points earned for each student for a particular section, // based on the number of sections each student attended. // Returns the data as an array. public static int[] computePoints(int[] attended) { int[] points = new int[5]; for (int i = 0; i < attended.length; i++) { points[i] = Math.min(20, 3 * attended[i]); } return points; } // Computes the percentage for each student for a particular section. // Returns the data as an array. public static double[] computeGrades(int[] points) { double[] grades = new double[5]; for (int i = 0; i < points.length; i++) { grades[i] = 100.0 * points[i] / 20.0; } return grades; } }