Write a Java program called RandomNumberAverage. This program will create a file
ID: 3714597 • Letter: W
Question
Write a Java program called RandomNumberAverage. This program will create a file. You should submit both the Java program and the file that is created. You will use the Random class, to create 10 random integers. You will write these integers to the file and close the file. Then you will open the file, read in the 10 integers, and find the average of the integers. The program will print out the average. You will submit both the Java program and the file that you created. Write a Java program called RandomNumberAverage. This program will create a file. You should submit both the Java program and the file that is created. You will use the Random class, to create 10 random integers. You will write these integers to the file and close the file. Then you will open the file, read in the 10 integers, and find the average of the integers. The program will print out the average. You will submit both the Java program and the file that you created. Write a Java program called RandomNumberAverage. This program will create a file. You should submit both the Java program and the file that is created. You will use the Random class, to create 10 random integers. You will write these integers to the file and close the file. Then you will open the file, read in the 10 integers, and find the average of the integers. The program will print out the average. You will submit both the Java program and the file that you created.Explanation / Answer
Below is your code
RandFile.java
public class RandFile {
public static void main(String[] args) throws IOException {
DecimalFormat df = new DecimalFormat(".##");
Scanner scan = new Scanner(System.in);
System.out.println("Enter the filename : ");
String filename = scan.next();
File file = new File(filename);
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < 10; i++) {
int min = 10, max = 100;
int range = (max - min) + 1;
int x = (int) (Math.random() * range) + min;
bw.write(x + " ");
}
bw.close();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
System.out.println(line);
double sum = 0;
String[] numbers = line.split(" ");
for (int i = 0; i < numbers.length; i++) {
sum += Integer.parseInt(numbers[i]);
}
System.out.println("Average is : " + df.format(sum / numbers.length));
br.close();
}
}
Output
Enter the filename :
in.txt
11 32 26 76 41 97 38 19 29 23
Average is : 39.2
in.txt
11 32 26 76 41 97 38 19 29 23
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.