Post

Created by @nathanedwards
 at November 1st 2023, 6:19:26 am.

AP Computer Science Exam Question - Exception Handling

Write a Java program that reads a list of integers from a file and computes the average of these integers. The file "numbers.txt" contains one integer per line, and it may contain invalid inputs.

Your task is to implement the computeAverage method in the AverageCalculator class, which should take the filename as a parameter and return the average of the valid integers in the file. If any invalid or non-integer input is encountered in the file, it should be ignored and not included in the computation of the average.

Your solution should use exception handling to deal with any potential errors and provide a meaningful error message to the user if necessary.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AverageCalculator {
    public static double computeAverage(String filename) {
        double sum = 0.0;
        int count = 0;

        try {
            File file = new File(filename);
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

                try {
                    int number = Integer.parseInt(line);
                    sum += number;
                    count++;
                } catch (NumberFormatException e) {
                    // Ignore invalid inputs
                }
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        }

        if (count > 0) {
            return sum / count;
        } else {
            throw new IllegalArgumentException("No valid integers found in the file.");
        }
    }

    public static void main(String[] args) {
        String filename = "numbers.txt";
        double average = computeAverage(filename);
        System.out.println("Average: " + average);
    }
}

Explanation:

  • The AverageCalculator class provides a static method computeAverage that takes the filename as a parameter and returns the average of the valid integers in the file.
  • The method starts by initializing the sum and count variables to 0. These will be used to compute the average.
  • Within a try-catch block, it creates a File object using the filename and a Scanner object to read the file.
  • It then enters a loop that continues while the scanner has more lines to read. Inside the loop, it reads the next line using scanner.nextLine().
  • Within a nested try-catch block, it attempts to parse the current line as an integer using Integer.parseInt(). If successful, it adds the number to the sum and increments the count variable.
  • If the parsing fails and a NumberFormatException is caught, it ignores the invalid input and moves on to the next line.
  • Once the scanner has finished reading the file, it is closed.
  • If the file is not found, a FileNotFoundException is caught and an error message is printed to the console.
  • Finally, if there are valid integers in the file (count > 0), it returns the average (sum / count). Otherwise, it throws an IllegalArgumentException with an error message stating that no valid integers were found in the file.
  • In the main method, a filename is specified and the computeAverage method is called. The resulting average is then printed to the console.