/* Average.java by Craig Persiko
   
   Sample program to average all numbers from a file.
   CS 111A Solution to in-class exercise
*/

import java.io.*;
import java.util.Scanner;

public class Average
{
  public static void main(String[] args) throws IOException
  {
    final String OUTPUT_FILE_NAME = "average.txt";
    double sum = 0, average, num;
    int count;
    String filename;
    PrintWriter fOut = new PrintWriter(new File(OUTPUT_FILE_NAME));
    Scanner keyIn = new Scanner(System.in);

    System.out.println("Please enter the name of the input file");
    filename = keyIn.nextLine();
    // use the file name entered by the user, and open that file for input
    Scanner fileIn = new Scanner(new File(filename));

    for(count = 0; fileIn.hasNext(); count++)
    {
       num = fileIn.nextDouble();
       sum += num;
    }
    average = sum/count;

    fOut.println("The average of the " + count + " numbers in " + filename + " is: " + average);
    fOut.close();
    fileIn.close();

    System.out.println("Average saved to " + OUTPUT_FILE_NAME);
   }
}

/* Sample Output:

-bash-3.2$ cat nums.txt
5 10 7.5 8

94 30.22 1,100



-bash-3.2$ java Average
Please enter the name of the input file
nums.txt
Average saved to average.txt
-bash-3.2$ cat average.txt 
The average of the 7 numbers in nums.txt is: 179.24571428571429
-bash-3.2$ 

*/


syntax highlighted by Code2HTML, v. 0.9