Source of JavaAverage.java


  1: import java.io.File;
  2: import java.io.FileNotFoundException;
  3: import java.util.Scanner;

  5: /**
  6:  * A program to calculate the average of numbers entered by the user.
  7:  *
  8:  * @author Mark Young (A00000000)
  9:  */
 10: public class JavaAverage {

 12:     // only Scanner for System.in
 13:     public static Scanner fin;
 14:     public static final int MAX_FAILS = 3;
 15:     public static final Scanner KBD = new Scanner(System.in);

 17:     public static void main(String[] args) {
 18:         // Identify myself...
 19:         System.out.print("\n\n\n\n\n\n\n\n\n\n"
 20:                 + "Sample Program (Java)\n"
 21:                 + "=====================\n\n"
 22:                 + "Finds the average of positive integers "
 23:                 + "from a file.\n\n");
 24:         
 25:         fin = getTheScanner();

 27:         // Declare and initialize variables
 28:         int sum = 0;
 29:         int count = 0;
 30:         int n;

 32:         // keep going until the file ends
 33:         while (fin.hasNextInt()) {
 34:             n = fin.nextInt();
 35:             
 36:             // add the last number to the sum
 37:             sum += n;

 39:             // add one to the count
 40:             count++;
 41:         }

 43:         // Print the result
 44:         System.out.print("\n\nAverage = "
 45:                 + ((double)sum/(double)count)
 46:                 + ".\n\n");
 47:     }
 48:     
 49:     /**
 50:      * Create a Scanner connected to a file chosen by the user.
 51:      * User gets MAX_TRIES attempts to name a suitable file.
 52:      * 
 53:      * @return a Scanner connected to a user-chosen file
 54:      */
 55:     private static Scanner getTheScanner() {
 56:         for (int i = 1; i <= MAX_TRIES; ++i) {
 57:             System.out.print("Please enter the name of the input file: ");
 58:             String fileName = KBD.nextLine();
 59:             File theFile = new File(fileName);
 60:             try {
 61:                 return new Scanner(theFile);
 62:             } catch (FileNotFoundException ex) {
 63:                 System.out.println("Could not open " + fileName + " for input");
 64:             }
 65:         }
 66:         System.err.println("Too many failed names.  Quitting.");
 67:         System.exit(1);
 68:         return null;
 69:     }

 71: }