CSE142 Program Example: Arrays & Files handout #15
Input file section.txt
----------------------
1111111111
1110101101
1011110111
0110110111
1101101000
1110010001
1010010011
1010100101
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
-------------------------
// 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 MAX = 20; // max score for section attendance
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("section.txt"));
PrintStream output = new PrintStream(new File("output.txt"));
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 data = input.nextLine();
int[] scores = computeScores(data);
report(output, scores);
report(System.out, scores);
}
}
// computes and returns an array of scores for a series of boolean (0/1)
// section scores stored in the given String, making sure that no student
// goes over MAX points
public static int[] computeScores(String data) {
int[] scores = new int[data.length()];
int sum = 0;
for (int i = 0; i < data.length(); i++) {
char next = data.charAt(i);
if (next == '1') {
scores[i] = Math.min(3, MAX - sum);
sum += scores[i];
}
}
return scores;
}
// 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 < scores.length; i++) {
output.print(scores[i] + " ");
}
output.println();
}
}