The assignment here is to read a text file containing a list of numbers. We need to report how many numbers were in the file, the sum of all the numbers, the average of all numbers, and the minimum and maximum number.

First step is to read the file and for this we can use the Scanner class to read each number from a text file.

As we read each number we need to keep track of how many numbers we have read and a running total of the numbers read. Also need to check if each number is a new minimum or maximum.

Once we have read all the numbers from the file we can calculate the average value (we now know the total of all numbers read and how many numbers there were).

Finally we can output the results to the console. And we’re done.

Have a read through the code and try it out for yourself. As always, let us know if you have any questions.

package com.learnjava.math;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
try {
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
// Count how many numbers
int count = 0; // Count of numbers read
// Sum of all numbers
int total = 0;
// Smallest number
int min = Integer.MAX_VALUE;
// Largest number
int max = Integer.MIN_VALUE;
// Loop until no more numbers to be read from file
while (input.hasNext()) {
// Read next number from file
int next = input.nextInt();
// Increnment count
count++;
// Add number to total
total += next;
// Update minium
min = Math.min(min, next);
// Update maximum
max = Math.max(max, next);
}
input.close();
// All numbers have been read
// Can now calculate the average
// NB. This uses integer arithmetic so result will be rounded
int average = total / count;
// Finally display results to console
System.out.println(count+" numbers");
System.out.println("Sum of numbers "+total);
System.out.println("Smallest number "+min);
System.out.println("Largest number "+max);
System.out.println("Average of all numbers "+average);
} catch (FileNotFoundException ex) {
// We'll end up here if the file numbers.txt cannot be found
System.out.println("Could not find the output file");
}
}
}

*Related*