Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions