Average.java

Download Average.java source file

// Average.java - A program to read in a bunch of integers,
// and print all the numbers greater than the average.
// (Assume no more than 25 numbers total.)
//
// Note this code is not "production quality", in the interest of
// highlighting array code.  In real life there would be an array
// of, say, Student objects (with "name" and "GPA" properties).
// Also the Student information would likely come from a file or
// database, not the console.  An ArrayList would probably be
// a better choice for this particular application.  Finally the
// user interface is terrible: to avoid any Exception handling, any
// Exception at all aborts the program.  Not a good design!
//
// Written 1999 Wayne Pollock, Tampa FL USA.
// Modified 2004 by WP: added comments, cleaned up the style.
// Modified 2005 by WP: updated to use Java5 input methods.

import java.util.Scanner;

class Average
{
   private static final int MAX_NUM_OF_VALUES = 25;

   public static void main ( String [] args )
   {
      Scanner in = new Scanner( System.in );
      int[] vals = new int[MAX_NUM_OF_VALUES];
      int runningTotal = 0, numOfVals = 0;

      // Read and store values, while counting and summing them:
      System.out.println( "Enter integers, one per line (^Z to stop): " );
      while ( in.hasNextLine() )
      {
         vals[numOfVals] = Integer.parseInt( in.nextLine() );
         runningTotal += vals[numOfVals];
         ++numOfVals;
      }

      // Compute the average:
      if ( numOfVals == 0 )
         System.exit( 0 );
      double average = (double) runningTotal / numOfVals;

      // Display list of values greater than the average:
      System.out.println( "\nValues greater than " + average + ":\n" );
      for ( int i = 0; i < numOfVals; ++i )
      {
         if ( vals[i] > average )
            System.out.println( "\t" + vals[i] );
      }
   }
} // End of class Average