Post

Created by @nathanedwards
 at November 1st 2023, 2:15:53 am.

AP Computer Science Exam Question

Question

Write a Java program that reads a text file, data.txt, containing integers separated by spaces. Your program should calculate the average of these integers and print it to the console. If any exceptions occur during the file reading or calculation process, your program should catch the exception and print the error message "An error occurred" to the console.

Assume the following:

  • The data.txt file is in the same directory as the Java program.
  • Each line in the data.txt file contains only integers separated by spaces.
  • The data.txt file may contain an empty line or lines with spaces only.

Your program should include the following:

  1. A class called ExceptionHandling with a main method.
  2. A static method called calculateAverage that takes a String parameter representing the file name, and returns a double.
  3. The calculateAverage method should handle any exceptions related to file reading or calculation errors, and print the error message "An error occurred" if an exception occurs.
  4. The calculateAverage method should calculate the average of the integers read from the file and return it as a double.
  5. The main method should call the calculateAverage method, and print the result to the console.

Answer

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

public class ExceptionHandling {
    public static void main(String[] args) {
        double average = calculateAverage("data.txt");
        System.out.println("Average: " + average);
    }

    public static double calculateAverage(String fileName) {
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);

            int sum = 0;
            int count = 0;

            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    int number = scanner.nextInt();
                    sum += number;
                    count++;
                } else {
                    scanner.next();
                }
            }

            scanner.close();

            if (count == 0) {
                throw new ArithmeticException("Divide by zero");
            }

            return (double) sum / count;
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred: File not found");
        } catch (ArithmeticException e) {
            System.out.println("An error occurred: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An error occurred");
        }

        return 0.0;
    }
}

Explanation

  1. Firstly, an ExceptionHandling class is defined with a main method.
  2. The main method calls the calculateAverage method and stores the result in the average variable.
  3. The calculateAverage method takes a String parameter representing the file name and returns a double.
  4. Inside the calculateAverage method:
    • A File object is created using the given file name.
    • A Scanner object is created to read the file.
    • sum and count variables are initialized to 0.
  5. The program then enters a loop that continues until there are no more tokens in the file:
    • If the next token is an integer, it is added to the sum and the count is incremented.
    • If the next token is not an integer, it is skipped using scanner.next().
  6. After reading all the integers from the file, the scanner is closed.
  7. If the count is 0 (no integers were read), an ArithmeticException is thrown with a custom message.
  8. The average is calculated as the sum divided by the count and returned as a double.
  9. If any exceptions occur during the file reading or calculation process:
    • If a FileNotFoundException occurs, the message "An error occurred: File not found" is printed.
    • If an ArithmeticException occurs (divide by zero), the corresponding message is printed.
    • If any other exception occurs, the generic message "An error occurred" is printed.
  10. Finally, in the main method, the calculated average is printed to the console.