previous | start | next

Example 1b

This is the same example, but reads input from a file and uses the Java API Scanner class for input.

    1   import java.util.Scanner;
    2   
    3   public class AverageY {
    4   
    5     public static Scanner openInput(String fileName) {
    6       Scanner in = null;
    7       try {
    8         in = new Scanner(new File(fileName));
    9       } catch(FileNotFoundException e) {
   10         System.out.println("Cannot open input file: " + fileName);
   11         System.exit(0);
   12       }
   13       return in;
   14     }
   15   
   16     public static void main(String[] args) {
   17   
   18       Scanner stdin = new Scanner(System.in);
   19       String fname;
   20   
   21       System.out.print("Input file: ");
   22       fname = stdin.next();
   23   
   24       Scanner in = openInput(fname);
   25       
   26       int count = 0;       // number input values
   27       double sum = 0.0;    // sum of input values
   28   
   29       // read data and compute statistics
   30       while (in.hasNextDouble()) {
   31         double value = in.readDouble();
   32         sum += value;
   33         count++;
   34       }
   35   
   36       // compute the average
   37       double average = sum / count;
   38   
   39       // print results
   40       StdOut.println("Average is " + average);
   41     }
   42   }


previous | start | next