Problem Statement Read double values from a file called scor

Problem Statement: Read double values from a file called scores.txt and
calculate the average of these values.

Create a new project called ‘Lab5-FileContentsAverager’. Add a new Class file
called ‘FileContentsAverager’ and populate it with the code needed to
implement the sample output below. Note that the average will of course
depend on the contents of the scores.txt file.

You may use this template:

The average of the contents of scores.txt\' is 76.33333333333333

Solution

FileContentsAverager.java

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

public class FileContentsAverager {

public static void main(String[] args) throws IOException {
  
File file = new File(\"scores.txt\");
Scanner scanner = new Scanner(file);
double sum = 0;
int count = 0;
while(scanner.hasNextDouble()){
   sum = sum + scanner.nextDouble();
   count++;
}
double average = sum/count;
System.out.println(\"The average of the contents of \'scores.txt\' is \"+average);

}

}

Output:

The average of the contents of \'scores.txt\' is 6.200000000000001

scores.txt

11.1
2.2
3.3
4.4
5.5
6.6
7.7
8.8

Problem Statement: Read double values from a file called scores.txt and calculate the average of these values. Create a new project called ‘Lab5-FileContentsAve

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site