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

8.6 Program 8: Input from a file The program is to read a set of integers from a

ID: 3605806 • Letter: 8

Question

8.6 Program 8: Input from a file The program is to read a set of integers from a file (file name such as data.txt); the program then calculates the sums and the averages of the integers You need to use Scanner, FilelnputStream, IOException, and ArrayList classes. You MUST use at least two methods with the following headings: public static int sum (ArrayList array) //calculate sum of the integers public static double average (ArrayList array, int total) //calculate average of the integers You should use hasNext0 method in the Scanner class to control the loop for reading integers from the file (1) Prompting the user to enter a file, then input all the integers in the file into array and the output them (2 points) Ex Enter the file name> The data in the file is 10 14-45 30 -50 19 0 88 2) Complete the sum (ArrayList a) and average (ArrayList a, int total) (4 points) (3) In main0.call the both sum and average methods, then output the results.(4 points) Ex Enter the file name> The data in the file is

Explanation / Answer

ReadFileAndCalcAverage.java

import java.io.FileInputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;

public class ReadFileAndCalcAverage {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter the file name > ");

String fileName = input.next();

try{

ArrayList<Integer> list = new ArrayList<Integer>();

Scanner scan = new Scanner(new FileInputStream(fileName));

while(scan.hasNextInt()) {

list.add(scan.nextInt());

}

System.out.println("The data in the file is:");

for(Integer i: list) {

System.out.print(i+" ");

}

System.out.println();

int total = sum(list);

double avg = average(list, total);

System.out.println("The sum of all the data is "+total);

System.out.println("The average of all the data is "+avg);

} catch(IOException e) {

System.out.println("Error Occured: "+e.toString());

}

}

public static int sum(ArrayList<Integer> array) {

int sum = 0;

for(Integer i: array) {

sum+=i;

}

return sum;

}

public static double average(ArrayList<Integer> array, int total) {

return total/(double)array.size();

}

}

Output:

Enter the file name >
D:\data.txt
The data in the file is:
10 14 -45 30 -50 19 0 88
The sum of all the data is 66
The average of all the data is 8.25

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