Average.java

Download Average.java

 1: // Average.java - A program to read in a bunch of integers,
 2: // and print all the numbers greater than the average.
 3: // (Assume no more than 25 numbers total.)
 4: //
 5: // Note this code is not "production quality", in the interest of
 6: // highlighting array code.  In real life there would be an array
 7: // of, say, Student objects (with "name" and "GPA" properties).
 8: // Also the Student information would likely come from a file or
 9: // database, not the console.  An ArrayList would probably be
10: // a better choice for this particular application.  Finally the
11: // user interface is terrible: to avoid any Exception handling, any
12: // Exception at all aborts the program.  Not a good design!
13: //
14: // Written 1999 Wayne Pollock, Tampa FL USA.
15: // Modified 2004 by WP: added comments, cleaned up the style.
16: // Modified 2005 by WP: updated to use Java5 input methods.
17: 
18: import java.util.Scanner;
19: 
20: class Average
21: {
22:    private static final int MAX_NUM_OF_VALUES = 25;
23: 
24:    public static void main ( String [] args )
25:    {
26:       Scanner in = new Scanner( System.in );
27:       int[] vals = new int[MAX_NUM_OF_VALUES];
28:       int runningTotal = 0, numOfVals = 0;
29: 
30:       // Read and store values, while counting and summing them:
31:       System.out.println( "Enter integers, one per line (^Z to stop): " );
32:       while ( in.hasNextLine() )
33:       {
34:          vals[numOfVals] = Integer.parseInt( in.nextLine() );
35:          runningTotal += vals[numOfVals];
36:          ++numOfVals;
37:       }
38: 
39:       // Compute the average:
40:       if ( numOfVals == 0 )
41:          System.exit( 0 );
42:       double average = (double) runningTotal / numOfVals;
43: 
44:       // Display list of values greater than the average:
45:       System.out.println( "\nValues greater than " + average + ":\n" );
46:       for ( int i = 0; i < numOfVals; ++i )
47:       {
48:          if ( vals[i] > average )
49:             System.out.println( "\t" + vals[i] );
50:       }
51:    }
52: } // End of class Average