Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

We want code in a method to open the input file data.txt, input the data into an

ID: 3894858 • Letter: W

Question

We want code in a method to open the input file data.txt, input the data into an array, and compute and output the average of the input values. The array is declared as follows: int[ ] array = new int[100]; Provide the appropriate code to open the file, input all values until you reach the end of the file inserting each value into the array, close the file, compute the average and output the result. Place this code in a try block. Follow your try block with all of the catch blocks you feel are necessary to handle any error that might arise. Each catch should only catch a specific type of Exception (i.e., don't just use one catch block to catch all Exceptions). All of the catches can simply just output the message passed to it.

Explanation / Answer

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class ReadAndPrintScores{

public static void main(String args[]) {

try {

int[ ] array = new int[100];

int count = 0, sum = 0;

BufferedReader b;

String line = "";

b = new BufferedReader(new FileReader("data.txt"));

while((line = b.readLine()) != null) {

String[] numbers = line.split(" ");

for(int j = 0; j < numbers.length; j++)

array[count++] = Integer.parseInt(numbers[j]);

}

for(int i = 0; i < array.length; i++)

sum += array[i];

System.out.println("Average = " + sum);

}

catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

**Comment for any further queries.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote