Question: JAVA: Create a class that reads the file you made in the last exercise. Read all 1000 numbers, add them up and get the average.

JAVA:

Create a class that reads the file you made in the last exercise. Read all 1000 numbers, add them up and get the average. Also find the max and the min. Print them out and compare with what you calculated last time. determine the most frequent number and compare with the last time also.

Previous exercise:

Create a file. Generate 1000 random integers between 1 and 100. Write the integers to the file. Find the average of the numbers, the largest and the smallest. Write these to the file also. determine the most frequent number. Write it to the file.

Solution for previous exercise:

import java.util.*; import java.io.*; class Solution { public static void main(String[] args) { try{ int[] arr = new int[1000]; int[] count = new int[101]; Random rand = new Random(); int i; int largest = Integer.MIN_VALUE; int smallest = Integer.MAX_VALUE; int sum = 0; for( i = 0 ; i < 1000 ; i++ ) { arr[i] = rand.nextInt( 100 ) + 1; count[ arr[i] ]++; sum += arr[i]; if( arr[i] > largest ) largest = arr[i]; if( arr[i] < smallest ) smallest =arr[i]; } double average = (double)sum / 1000.0; int most_frequent = -1; int freq = -1; for( i = 1 ; i <= 100 ; i++ ) { if( count[i] > freq ) { freq = count[i]; most_frequent = i; } } FileWriter fw = new FileWriter("output.txt"); fw.write("1000 integers are ... "); for( i = 0 ; i < 1000 ; i++ ) fw.write( String.valueOf(arr[i]) + " " ); fw.write(" Largest Element : " + String.valueOf(largest)); fw.write(" Smallest Element : " + String.valueOf(smallest)); fw.write(" Average : " + String.valueOf(average)); fw.write(" Most Frequent Element : " + String.valueOf(most_frequent)); fw.close(); } catch(Exception e) { e.printStackTrace(); } } }

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!