Post

Created by @nathanedwards
 at November 1st 2023, 8:21:33 am.

AP Computer Science Exam Question

You are tasked with writing a program that reads a list of integers from a file called "numbers.txt" and calculates the average of the numbers. However, the file may contain non-integer values or be empty. Implement the program using exception handling to handle possible errors and ensure correct calculation of the average.

Write a program that includes the following:

  1. Define a method named calculateAverage that takes no parameters and returns a double. This method should implement the necessary code to read the integers from "numbers.txt" file, calculate the average, and return it.

  2. Implement the calculateAverage method to handle the following exceptions: a. If the file does not exist, print "File not found." and return 0. b. If the file is empty, print "File is empty." and return 0. c. If any non-integer values are encountered while reading the file, print "Invalid data found." and skip those values.

  3. In the main method, call the calculateAverage method and print the calculated average, formatted with two decimal places.

You may assume that the file "numbers.txt" is located in the same directory as the program file.

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

public class AverageCalculator {
    public static void main(String[] args) {
        double average = calculateAverage();
        System.out.printf("Average: %.2f%n", average);
    }
    
    public static double calculateAverage() {
        try {
            File file = new File("numbers.txt");
            Scanner scanner = new Scanner(file);
            int count = 0;
            int sum = 0;
            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    sum += scanner.nextInt();
                    count++;
                } else {
                    scanner.next(); // Skip non-integer value
                    System.out.println("Invalid data found.");
                }
            }
            scanner.close();
            
            if (count == 0) {
                System.out.println("File is empty.");
                return 0;
            } else {
                return (double) sum / count;
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
            return 0;
        }
    }
}

Explanation:

  1. The code starts by defining the calculateAverage method which returns a double value. It also defines the main method where the program execution starts.

  2. Inside the calculateAverage method, a File object is created with the name "numbers.txt". Then, a Scanner object is created to read the contents of the file. Two variables count and sum are initialized to keep track of the number of integers read and their sum, respectively.

  3. A while loop is used to iterate through the file contents. The loop continues as long as the scanner has more elements. Inside the loop, the hasNextInt method is used to check if the next token in the file is an integer. If it is, the integer value is added to the sum and the count is incremented. If it is not an integer, the next method is called to skip the non-integer value and a corresponding error message is printed.

  4. Once all the integers have been read, the scanner is closed.

  5. After the loop, there is a check to see if the count variable is still 0. If it is, it means the file was empty, and the error message "File is empty." is printed before returning 0.

  6. If the file was not empty, the average is calculated by dividing the sum by the count as a floating-point value. The average is then returned.

  7. In the main method, the calculateAverage method is called and the result is stored in the average variable. The average is printed using System.out.printf with two decimal places.