Question: How do I make my java program read integers that were printed to a text file and get/display the average? The description for this program

How do I make my java program read integers that were printed to a text file and get/display the average?

The description for this program is below:

Create an application which 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.

My code is below:

import java.io.File;

import java.io.IOException;

import java.util.Scanner;

public class RandomNumbers {

public static void main(String args[]) throws IOException

{

Scanner s = new Scanner(new File("labNine.txt"));

double sum =0.0;

while(s.hasNextDouble()) {

sum += s.nextDouble();

System.out.println("sum:" + sum);

System.out.println("Average : "+ sum/20);

}

s.close();

Below is the code used to create the file:

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

public class RandomAverage{

public static void main(String[]args) throws IOException{

String filename = "labNine.txt";

PrintWriter writer = null;

try {

//first parameter is filename next parameter is boolean expression append.

//True: means yes I want to append. False means: rewrite

FileWriter fw = new FileWriter(filename, false);

//Pass file writer

writer = new PrintWriter(fw);

}

catch(FileNotFoundException e) {

e.printStackTrace();

}

catch(IOException f) {

f.printStackTrace();

}

for(int count = 1; count<=20; count++) {

int random = 1 + (int)(Math.random()*100);

System.out.println(random);

writer.println("Random Numbers: " + random);

}

writer.close();

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!