CSE142 Program Example handout #18 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 Log of execution ---------------- This program processes an input file of numbers. What is the name of the input file? foo.txt File not found. Please try again. What is the name of the input file? numbers.dat File not found. Please try again. What is the name of the input file? numbers.txt 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 // 11/8/04 // // 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.*; public class Numbers { public static void main(String[] args) { System.out.println("This program processes an input file of numbers."); System.out.println(); Scanner console = new Scanner(System.in); Scanner input = getInput(console); process(input); } // prompts the user for a file name and reads the result using the // console Scanner until the user gives a legal file name public static Scanner getInput(Scanner console) { Scanner result = null; while (result == null) { System.out.print("What is the name of the input file? "); String name = console.nextLine(); try { result = new Scanner(new File(name)); } catch (FileNotFoundException e) { System.out.println("File not found. Please try again."); } } System.out.println(); return result; } // 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(); } }
Stuart Reges
Last modified: Mon Nov 8 10:58:17 PST 2004