/* Marty Stepp, CSE 142, Spring 2010 ** This second version breaks the code into methods for better style. ** This program reads a file representing which students attended which discussion sections and produces output of their scores and grades. Each line of the file has 45 characters split into nine 5-letter sections. An 'a' means the student was absent, an 'n' means they attended but didn't do the section problems, and a 'y' means they did the problems. The purpose of the program is to demonstrate using an array for tallying, and to demonstrate text processing with the char data type. Example input: yynyyynayayynyyyayanyyyaynayyayyanayyyanyayna ayyanyyyyayanaayyanayyyananayayaynyayayynynya yyayaynyyayyanynnyyyayyanayaynannnyyayyayayny Example output: Section 1 Student points: [20, 17, 19, 16, 13] Student grades: [100.0, 85.0, 95.0, 80.0, 65.0] Section 2 Student points: [17, 20, 16, 16, 10] Student grades: [85.0, 100.0, 80.0, 80.0, 50.0] Section 3 Student points: [17, 18, 17, 20, 16] Student grades: [85.0, 90.0, 85.0, 100.0, 80.0] */ import java.io.*; import java.util.*; public class Sections2 { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); int section = 1; while (input.hasNextLine()) { // process one section String line = input.nextLine(); int[] points = countPoints(line); double[] grades = computeGrades(points); results(section, points, grades); section++; } } // Computes the points earned for each student for a particular section. // Look at the pattern of character indexes to student index. // It wraps around every 5 characters... // student 01234012340123401234... // index 01234567890123456789... // line = "yynyyynayayynyyyayanyyyaynayyayyanayyyanyayna" public static int[] countPoints(String line) { int[] points = new int[5]; for (int i = 0; i < line.length(); i++) { int index = i % 5; int earned = 0; if (line.charAt(i) == 'y') { // c == 'y' or 'n' or 'a' earned = 3; } else if (line.charAt(i) == 'n') { earned = 2; } // cap the points at 20 for each student points[index] = Math.min(20, points[index] + earned); } return points; } // Computes the percentage for each student for a particular section. 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; } // Produces all output about a particular section. public static void results(int section, int[] points, double[] grades) { System.out.println("Section " + section); System.out.println("Student scores: " + Arrays.toString(points)); System.out.println("Student grades: " + Arrays.toString(grades)); System.out.println(); } }