I need help writing this program in JAVA, this is an introductory java course, s
ID: 3817749 • Letter: I
Question
I need help writing this program in JAVA, this is an introductory java course, so if possible, keep it as basic/simple as possible while still following the instructions. The output should look like the sample execution at the end of the problem.
Write a program that will find the average of a list of numbers found in a file.
Input Validation:
No input validation required. Assume the input file will have the correct type of data.
Requirements:
The program must ask the user for the name of the file.
You must have a method with the following header: public static double deviation(File inputFile)
This method will take a File object as input and use File I/O to calculate and return the standard deviation of a series of numbers found inside of a file.
You should create your own test files to test the functionality of your program.
Sample Execution:
Explanation / Answer
Program to calculate standard deviation of numbers from a file
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Deviation {
public static void main(String args[]) throws IOException
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String fileName = s.next();
double dev = deviation(new File(fileName));
System.out.println("The standard deviation of the values in this file is: "+((double)Math.round(dev*100)/100)); //To show only two decimal places
s.close();
}
private static double deviation(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
List<Double> numbers = new ArrayList<Double>();
List<Double> diffList = new ArrayList<Double>();
String str="";
double num,sum=0,mean=0;
int n=0;
while((str=br.readLine())!=null)
{
num = Double.parseDouble(str);
numbers.add(num);
sum += num;
n++;
}
br.close();
mean = sum/n; //Taking the mean of all numbers
sum=0;
for(int i=0;i<n;i++)
{
double temp = numbers.get(i)-mean;
temp = temp*temp; //temp stores squared difference of mean and current number
diffList.add(temp);
sum += temp; //Sum of difference of mean and numbers
}
double average = sum/n; //It stores the average of the difference of mean and numbers
return Math.sqrt(average); //Square root of average returns the standard deviation
}
}
my_numbers.txt
9
2
5
4
12
7
8
11
9
3
7
4
12
5
4
10
9
6
9
4
Output
Enter the name of the file: my_numbers.txt
The standard deviation of the values in this file is: 2.98