Write a program that takes its input from a text file of strings representing numbers of type double. The program outputs to the screen the average and standard deviation of the numbers in the file. The file contains nothing but strings representing numbers of type double , one per line. The standard deviation of a list of numbers , , , and so forth is defined as the square root of the average of the following numbers:
, , , and so forth.
The number a is the average of the numbers , , , and so forth. Hint: Write your program so that it first reads the entire file and computes the average of all the numbers, then closes the file, and then reopens the file and computes the standard deviation. You will find it helpful to first do Programming Project 10.3 and then modify that program in order to obtain the program for this project.
PROGRAM CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class NumberStats {
public static void main(String[] args) {
// File path of the input text file
String filePath = "input.txt";
// Read the numbers from the file and calculate the average
double average = calculateAverage(filePath);
// Reopen the file and calculate the standard deviation
double standardDeviation = calculateStandardDeviation(filePath, average);
// Output the average and standard deviation to the screen
System.out.println("Average: " + average);
System.out.println("Standard Deviation: " + standardDeviation);
}
// Method to read numbers from the file and calculate the average
private static double calculateAverage(String filePath) {
double sum = 0.0;
int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
double num = Double.parseDouble(line);
sum += num;
count++;
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
System.exit(1);
} catch (NumberFormatException e) {
System.err.println("Error parsing a number from the file: " + e.getMessage());
System.exit(1);
}
// Calculate the average
return sum / count;
}
// Method to calculate the standard deviation
private static double calculateStandardDeviation(String filePath, double average) {
double sumSquaredDiff = 0.0;
int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
double num = Double.parseDouble(line);
double diff = num - average;
sumSquaredDiff += diff * diff;
count++;
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
System.exit(1);
} catch (NumberFormatException e) {
System.err.println("Error parsing a number from the file: " + e.getMessage());
System.exit(1);
}
// Calculate the standard deviation
return Math.sqrt(sumSquaredDiff / count);
}
}
DATA IN INPUT FILE(input.txt):
3.5
2.0
4.5
5.2
OUTPUT:
Average: 3.3
Standard Deviation: 1.1832159566199232