// A version of the Sections program that is decomposed into methods. // To do this we must pass arrays as parameters and use them as return values. 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")); while (input.hasNextLine()) { String line = input.nextLine(); int[] attended = computeAttended(line); System.out.println("Sections attended: " + Arrays.toString(attended)); int[] scores = computeScores(attended); System.out.println("Student scores: " + Arrays.toString(scores)); double[] grades = computeGrades(scores); System.out.println("Student grades: " + Arrays.toString(grades)); System.out.println(); } } // Reads the line of text representing section attendance and returns // an array representing how many sections each student attended. // // Example input: line = 111111101011111101001110110110110001110010100 // Example return: attended = {9, 6, 7, 4, 3} public static int[] computeAttended(String line) { int[] attended = new int[5]; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); // int studentNumber = i % 5; if (c == '1') { // the student attended that week's section attended[i % 5]++; } } return attended; } // Reads the array of sections attended and returns a new array // representing the section points scored by each student. // Each section is worth 3 points up to a maximum of 20. // // Example input: attended = {9, 6, 7, 4, 3} // Example return: scores = {20, 18, 20, 12, 9} public static int[] computeScores(int[] attended) { int[] scores = new int[5]; for (int i = 0; i < scores.length; i++) { scores[i] = Math.min(20, 3 * attended[i]); } return scores; } // Reads the array of section points and returns a new array // representing the grade percentages for each student. // The maximum is 20 points, so percentages come from dividing by 20. // // Example input: studentScores = {20, 18, 20, 12, 9} // Example return: grades = {100.0, 90.0, 100.0, 60.0, 45.0} public static double[] computeGrades(int[] scores) { // Percents: 100 90 90 75 60 double[] grades = new double[5]; for (int i = 0; i < scores.length; i++) { grades[i] = 100.0 * scores[i] / 20; } return grades; } }