CSE142 Program Example handout #22 Input file section.txt ---------------------- 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1 0 0 0 1 1 1 0 0 1 0 0 0 1 1 0 1 0 0 1 0 0 1 1 1 0 1 0 1 0 0 1 0 1 Output file section.out ----------------------- 3 3 3 3 3 3 2 0 0 0 3 3 3 0 3 0 3 3 0 2 3 0 3 3 3 3 0 3 2 0 0 3 3 0 3 3 0 3 3 2 3 3 0 3 3 0 3 0 0 0 3 3 3 0 0 3 0 0 0 3 3 0 3 0 0 3 0 0 3 3 3 0 3 0 3 0 0 3 0 3 Program file Section.java ------------------------- // Stuart Reges // 2/24/05 // // This program converts an input file of section attendance scores from a // boolean (0/1) form to a numerical form. A 0 means someone did not attend, // a 1 means they did attend. Students get 3 points for each section they // attend with a maximum of 20 points. The input file consists of input lines // each of which have one student's attendance record in the 0/1 form. The // output file lists the corresponding points for attendance. The output is // also echoed to System.out. import java.io.*; import java.util.*; public class Section { public static final int SECTIONS = 10; // # of section scores per line public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("section.txt")); PrintStream output = new PrintStream(new File("section.out")); processFile(input, output); } // processes the given input file, sending a report to the given output public static void processFile(Scanner input, PrintStream output) { while (input.hasNextLine()) { String text = input.nextLine(); Scanner data = new Scanner(text); int[] scores = new int[SECTIONS]; fillIn(scores, data); report(output, scores); report(System.out, scores); } } // fills in the scores for a series of boolean (0/1) section scores // stored in the given scanner, making sure that no student goes over // 20 points public static void fillIn(int[] scores, Scanner data) { int sum = 0; for (int i = 0; i < SECTIONS; i++) { int next = data.nextInt(); if (next == 1 && sum < 18) { scores[i] = 3; } else if (next == 1 && sum == 18) { scores[i] = 2; } else { scores[i] = 0; } sum += scores[i]; } } // reports a set of scores on a single line of output to the given // print stream public static void report(PrintStream output, int[] scores) { for (int i = 0; i < SECTIONS; i++) { output.print(scores[i] + " "); } output.println(); } }
Stuart Reges