import java.io.*;
import java.text.*;
public class ArrayOfObjects
{
public static void main (String [] args)
{
Roster roster
= new Roster ();
roster.readList
();
roster.displayList
();
}
} // ArrayOfObjects
// The Student class stores information about a single student.
class Student
{
String id, name;
double qpa;
Student (String ID)
{
id = ID;
name = "";
qpa = 0;
} // constructor
// readData uses a BufferedReader to read
in data about a single student.
public void readData (BufferedReader infile)
throws IOException
{
try
{
name = infile.readLine ();
qpa = Double.parseDouble (infile.readLine ());
} catch (NumberFormatException
e)
{
System.out.println ("Number Format Exception in the qpa for " + name);
}
} // readData
// displayData prints the data for a student
out on the screen.
public void displayData ()
{
System.out.println
("ID: " + id);
System.out.println
("Name: " + name);
System.out.println
("QPA: " + decimals (qpa));
System.out.println
();
} // displayData
// decimals formats a double for printing
with two decimal places.
private String decimals (double num)
{
DecimalFormat
decFor = new DecimalFormat ();
decFor.setMaximumFractionDigits
(2);
decFor.setMinimumFractionDigits
(2);
return decFor.format
(num);
} // decimals
} // Student
/*The Roster class maintains an array of students. It reads in
the data from a file and displays it on the screen. */
class Roster
{
final int maxSize = 10;
Student [] list = new Student [maxSize];
int listSize = 0;
// readList opens a file and reads the data
into an array of objects.
public void readList ()
{
try
{
BufferedReader infile = new BufferedReader (new InputStreamReader (new
FileInputStream ("students.txt")));
String id = infile.readLine ();
while ((id != null) && (listSize < maxSize))
{
Student student = new Student (id);
student.readData (infile);
list [listSize] = student;
listSize ++;
id = infile.readLine ();
}
infile.close ();
} catch (IOException
e) {System.out.println ("File not found");}
} // readList
// displayList prints the contents of the
array out to the screen.
public void displayList ()
{
for (int count
= 0; count < listSize; count ++)
{
System.out.println ();
list [count].displayData ();
}
} // displayList
} // Roster