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:
data.txt file is in the same directory as the Java program.data.txt file contains only integers separated by spaces.data.txt file may contain an empty line or lines with spaces only.Your program should include the following:
ExceptionHandling with a main method.calculateAverage that takes a String parameter representing the file name, and returns a double.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.calculateAverage method should calculate the average of the integers read from the file and return it as a double.main method should call the calculateAverage method, and print the result to the console.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;
}
}
ExceptionHandling class is defined with a main method.main method calls the calculateAverage method and stores the result in the average variable.calculateAverage method takes a String parameter representing the file name and returns a double.calculateAverage method:
File object is created using the given file name.Scanner object is created to read the file.sum and count variables are initialized to 0.sum and the count is incremented.scanner.next().scanner is closed.count is 0 (no integers were read), an ArithmeticException is thrown with a custom message.sum divided by the count and returned as a double.FileNotFoundException occurs, the message "An error occurred: File not found" is printed.ArithmeticException occurs (divide by zero), the corresponding message is printed.main method, the calculated average is printed to the console.