CSE142 Program Example handout #21
Input file numbers.txt
----------------------
85 93.2 97.5 18.5 394.23
-18 45.2 19.8 47.3
42
8 8 8 8 32
2.4 -2.4 3.5 -500
Program Output
--------------
Total numbers = 5
average = 137.686
minimum = 18.5
maximum = 394.23
Total numbers = 4
average = 23.575
minimum = -18.0
maximum = 47.3
Total numbers = 1
average = 42.0
minimum = 42.0
maximum = 42.0
Total numbers = 5
average = 12.8
minimum = 8.0
maximum = 32.0
Total numbers = 4
average = -124.125
minimum = -500.0
maximum = 3.5
Program file Numbers.java
-------------------------
// Stuart Reges
// 2/14/05
//
// This program processes an input file of numbers, reporting for each line of
// input the number of numbers and their average, minimum and maximum.
import java.io.*;
import java.util.*;
public class Numbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("numbers.txt"));
process(input);
}
// processes an entire input file line by line
public static void process(Scanner input) {
while (input.hasNextLine()) {
String text = input.nextLine();
Scanner data = new Scanner(text);
processLine(data);
}
}
// processes a series of numbers from the given Scanner, reporting
// the number of numbers along with the average, minimum and maximum
// of the numbers; assumes that at least one number can be read
public static void processLine(Scanner data) {
// read first number outside the loop to initialize min/max
double next = data.nextDouble();
double sum = next;
double min = next;
double max = next;
int count = 1;
while (data.hasNextDouble()) {
next = data.nextDouble();
sum += next;
count++;
if (next < min)
min = next;
if (next > max)
max = next;
}
reportResults(count, sum/count, min, max);
}
// reports the overall statistics for a group of numbers
public static void reportResults(int count, double average,
double min, double max) {
System.out.println("Total numbers = " + count);
System.out.println("average = " + average);
System.out.println("minimum = " + min);
System.out.println("maximum = " + max);
System.out.println();
}
}