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:
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.sum and count variables to 0. These will be used to compute the average.File object using the filename and a Scanner object to read the file.scanner.nextLine().Integer.parseInt(). If successful, it adds the number to the sum and increments the count variable.NumberFormatException is caught, it ignores the invalid input and moves on to the next line.FileNotFoundException is caught and an error message is printed to the console.IllegalArgumentException with an error message stating that no valid integers were found in the file.main method, a filename is specified and the computeAverage method is called. The resulting average is then printed to the console.