Computer Science, asked by pranavtri00, 4 months ago

Open and read a file of integers into an array that is created with the first integer telling you how many to read.

So 4 9 11 12 15 would mean create an int array size 4 and read in the remaining 4 values into data[].

Then compute their average as a double and their max as an int. Print all this out neatly to the screen and to an output file named answer-hw3.

Answers

Answered by ItzMsSachita
4

Answer:

Input : 5, 4, 6, 9, 10 Output : 9 10 Explanation: avg = 5 + 4 + 6 + 9 + 10 / 5; avg = 34 ... Recommended: Please try your approach on {IDE} first, before moving on to the solution. ... Print array elements greater than average ... double avg = 0;. for ( int i = 0; i < n; i++) ...

Answered by AadilAhluwalia
0

It also computes their average and maximum values and writes the results to an output file named "answer-hw3":

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class ReadIntegersFromFile {

   public static void main(String[] args) {

       try {

          // Open the input file for reading

           File inputFile = new File("input.txt");

           Scanner scanner = new Scanner(inputFile);

          // Read the first integer to determine array size

           int arraySize = scanner.nextInt();

           int[] data = new int[arraySize];

          // Read the remaining integers into the array

           for (int i = 0; i < arraySize; i++) {

               data[i] = scanner.nextInt();

           }

          // Calculate the average of the integers

           double sum = 0;

           for (int i = 0; i < arraySize; i++) {

               sum += data[i];

           }

           double average = sum / arraySize;

          // Find the maximum integer in the array

           int max = data[0];

           for (int i = 1; i < arraySize; i++) {

               if (data[i] > max) {

                   max = data[i];

               }

           }

          // Open the output file for writing

           File outputFile = new File("answer-hw3.txt");

           FileWriter writer = new FileWriter(outputFile);

          // Print the results to the console and the output file

           System.out.printf("Average: %.2f\n", average);

           System.out.printf("Max: %d\n", max);

           writer.write(String.format("Average: %.2f\n", average));

           writer.write(String.format("Max: %d\n", max));

           // Close the scanner and the writer

           scanner.close();

           writer.close();

       } catch (IOException e) {

           e.printStackTrace();

       }

   }

}

It then prints the results to the console and writes them to an output file named "answer-hw3.txt".

#SPJ3

Similar questions