Download AverageGPA.java source file
Download/view StudentRecords.txt data file
// AverageGPA.java - A program to read in a bunch of student records
// from a file, and print all student names who have a greater than
// average GPA (i.e., the Dean's list). The file format is:
// count_of_records (int) <newline>
// name (String) <tab> GPA (float) <newline>
//
// An ArrayList would probably be a better choice for this particular
// application, but I wanted to show array processing so I added a count
// of the records as the first line of the file. The file name is
// passed as a command line argument to the program.
//
// Written 2004 Wayne Pollock, Tampa FL USA.
import java.io.*;
import java.util.*;
public class AverageGPA
{
private static final String DELIMITER = "\t";
public static void main ( String [] args )
{
BufferedReader in = null;
int numRecords = 0;
Student [] student;
float runningTotal = 0.0f;
String record = null;
if ( args.length != 1 )
{ System.out.println( "\nUsage: java AverageGPA <name_of_datafile>" );
System.exit( -1 );
}
try
{ in = new BufferedReader( new FileReader( args[0] ) );
numRecords = Integer.parseInt( in.readLine() );
}
catch ( FileNotFoundException fnfe )
{ System.out.println( fnfe );
System.exit( -1 );
}
catch ( Exception e )
{ System.out.println( "\n*** Could not read number of records "
+ "(first line)!" );
System.exit( -1 );
}
student = new Student[numRecords];
for ( int i = 0; i < numRecords; ++i )
{
try
{ record = in.readLine();
}
catch ( IOException ioe )
{ System.out.println( "\n*** Unexpected End Of File (after line "
+ i + "!" );
System.exit( -1 );
}
String name = null;
float gpa = 0.0f;
try
{ StringTokenizer st = new StringTokenizer( record, DELIMITER );
name = st.nextToken();
gpa = Float.parseFloat( st.nextToken() );
}
catch ( Exception e )
{ System.out.println( "\n*** Bad Record (line " + (i+1)
+ ": " + record );
System.exit( -1 );
}
student[i] = new Student( name, gpa );
runningTotal += student[i].getGPA();
}
// Compute the average:
if ( numRecords == 0 )
System.exit( 0 );
double average = (double) runningTotal / numRecords;
System.out.println( "\n Dean's List (GPA greater than "
+ average + "):\n" );
for ( int i = 0; i < student.length; ++i )
{
if ( student[i].getGPA() > average )
System.out.println( "\t" + student[i] );
}
}
} // End of class AverageGPA
/** This is a trivial class Student, containing only a name and GPA:
*/
class Student
{
private String name;
private float gpa;
public Student ( String name, float gpa )
{ this.name = name;
this.gpa = gpa;
}
public String getName ()
{ return name;
}
public float getGPA ()
{ return gpa;
}
public String toString ()
{ return "Name: " + name + "\tGPA: " + Float.toString( gpa );
}
}