Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CSE142 handout #14 CSE142 Program Example: Arrays & Files handout #14 Input file section.txt ---------------------- 1111111111 1110101101 1011110111 0110110111 1101101000 1110010001 1010010011 1010100101 Output file output.txt ---------------------- 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 written assignment scores from a // boolean (0/1) form to a numerical form. A 0 means someone did not do the // written assignment, a 1 means they did. Students get 3 points for each // written assignment they complete with a maximum of 20 points. The input // file consists of input lines each of which have one student's written // assignment in the 0/1 form. The output file lists the corresponding points. // 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")); while (input.hasNextLine()) { String line = input.nextLine(); // two options for constructing an array: // 1) this method constructs it and passes it as a parameter // 2) the called method constructs it and returns it // here we use option 2: int[] scores = computeScores(line); print(output, scores); print(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 = sum + scores[i]; } } return scores; } // prints a set of scores on a single line of output to the given // print stream public static void print(PrintStream output, int[] scores) { for (int i = 0; i < scores.length; i++) { output.print(scores[i] + " "); } output.println(); } } Stuart Reges Last modified: Mon May 16 16:53:13 PDT 2022