208k views
5 votes
Assume a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that calculates the average of all the numbers stored in the file.

User Tashonda
by
6.8k points

1 Answer

3 votes

Answer:

Step-by-step explanation:

The following code is written in Java. It assumes that the numbers.txt file is in the same folder as the Java file and the numbers are separated one on each line. It reads the file, adds all the numbers to an array, then adds the numbers into a single variable and finally divides by the total amount of numbers in order to get the average.

public static void main(String[] args) {

ArrayList<Integer> numbers = new ArrayList();

try {

File myObj = new File("numbers.txt");

Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine();

numbers.add(Integer.parseInt(data));

}

myReader.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}

int average = 0;

for (int x:numbers) {

average += x;

}

average = average / numbers.size();

System.out.println(average);

}

User Kiran Mathew
by
6.3k points