In: Computer Science
****java*** Create an application that generates 20 random numbers between 1 and 100 and writes them to a text file on separate lines. Then the program should read the numbers from the file, calculate the average of the numbers, and display this to the screen.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
class random_numbers {
public static void main(String[] args) throws IOException {
Random rn = new Random();
// writes them to a text file on separate lines.
FileWriter output = new FileWriter("input.txt");
// generates 20 random numbers between 1 and 100
for (int i = 0; i < 20; i++)
output.write(Integer.toString(rn.nextInt(100) + 1) + "\n");
// close file
output.close();
// Then the program should read the numbers from the file,
File file = new File("input.txt");
Scanner input = new Scanner(file);
// calculate the average of the numbers,
double avg = 0;
for (int i = 0; i < 20; i++) {
avg += input.nextInt();
}
avg /= 20;
// close file
input.close();
// display this to the screen.
System.out.println("Average is: " + avg);
}
}
.
Output:
.