Post

Created by @nathanedwards
 at November 2nd 2023, 3:47:38 am.

AP Computer Science Exam Question

Reading and Writing Files

You have been given a text file called myData.txt that contains a list of numbers, one number per line. Each number in the file represents the score obtained by a student in a test. Your task is to write a program in Java that reads the scores from the file, calculates the average score, and writes the average to a new file called averageScore.txt.

Write the complete Java code to accomplish this task. Your code should include proper exception handling and should use file input/output streams for reading and writing files. Assume that the input file exists and is readable.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class AverageScoreCalculator {

    public static void main(String[] args) {
        String inputFile = "myData.txt";
        String outputFile = "averageScore.txt";
        int totalScores = 0;
        int numScores = 0;
        
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                int score = Integer.parseInt(line.trim());
                totalScores += score;
                numScores++;
            }
            
            double average = (double) totalScores / numScores;
            writer.write(String.format("%.2f", average));
            
            System.out.println("Average score calculated and written to " + outputFile);
            
        } catch (IOException e) {
            System.err.println("Error reading/writing file: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.err.println("Invalid number format in file: " + e.getMessage());
        }
    }
}

Explanation

  1. We start by declaring two variables: inputFile to store the name of the input file and outputFile to store the name of the output file. We also declare two variables: totalScores to store the sum of all scores and numScores to store the number of scores read from the file.

  2. We use the try-with-resources statement to automatically close the input and output streams after we're done with them. Within this block, we create a BufferedReader object to read from the input file and a BufferedWriter object to write to the output file.

  3. We use a loop to read each line from the input file. The loop continues until there are no more lines to read (readLine() returns null).

  4. For each line, we parse the string into an integer using Integer.parseInt(). We trim the line to remove any leading or trailing whitespace before parsing.

  5. We add the score to the totalScores variable and increment the numScores variable.

  6. After reading all the scores, we calculate the average by dividing totalScores by numScores and storing the result in the average variable.

  7. The average is then written to the output file using the write() method of the BufferedWriter object. We format the average to two decimal places using String.format().

  8. Finally, we print a message to the console indicating that the average score has been calculated and written to the output file.

  9. Any exceptions that occur during the file reading/writing or number parsing process are caught using catch blocks. If an exception occurs, an error message is printed to the console.

Make sure that the input file myData.txt is located in the same directory as the Java file, and the program will create the averageScore.txt file with the calculated average score.