TO DO: You will be provided with a text file that has a list of ratings (values
ID: 3713640 • Letter: T
Question
TO DO: You will be provided with a text file that has a list of ratings (values between 1 and 10) with multiple values on a line and multiple lines. For your testing, just create one with numbers of your choice. You need to write a program named Distribution.java that will read in the data and return a frequency distribution and an average value for the data. NOTE: you must let the user choose the file from a FileDialog box. Do not hard code the path location!
For instance, if the file had the following
1 6 8 7
2 5 8 9 9
3 4
2 3 9 9 8 8 7
10 1 10 10
3
Your program should return
The following is the distribution of values:
1 - 2
2 - 2
3 - 3
4 - 1
5 - 1
6 - 1
7 - 2
8 - 4
9 - 4
10 - 3
The average value was 6.17
Explanation / Answer
Given below is the code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you
save the following numbers into file ratings.txt and choose the file when the program runs
-----
1 6 8 7
2 5 8 9 9
3 4
2 3 9 9 8 8 7
10 1 10 10
3
Distribution.java
-----------
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Distribution {
public static void main(String[] args) {
FileDialog fd = new FileDialog((Frame)null, "Choose a file to open", FileDialog.LOAD);
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
int[] frequency = new int[11]; //frequency[0] is unused. frequency[1] stores frequency of number 1 and so on
if(directory != null && filename != null)
{
try {
Scanner inFile = new Scanner(new File(directory, filename));
double avg = 0;
int n = 0;
while(inFile.hasNextInt())
{
int value = inFile.nextInt();
frequency[value]++;
avg += value;
n++;
}
inFile.close();
avg /= n;
//display the frequencies
System.out.println("The following is the distribution of values");
for(int i = 1; i < 10; i++)
System.out.println(i + " - " + frequency[i]);
System.out.printf(" The average value was %.2f ", avg);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
}
output
------
The following is the distribution of values
1 - 2
2 - 2
3 - 3
4 - 1
5 - 1
6 - 1
7 - 2
8 - 4
9 - 4
The average value was 6.17
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.