// PersonArray2 Example // Test.java file import java.util.Scanner; import java.io.*; public class Test2 { // Throw FileNotFound exception if input // file cannot be opened public static void main(String[ ] args) throws FileNotFoundException { // Allocate Person array a. Person[ ] a = new Person[10]; // Create new scanner to read // from the file persons.txt. Scanner s = new Scanner( new File("persons.txt")); // lineNumber of file will be used // as array index. int lineNumber = 0; // Throw away first line of file. s.nextLine( ); // Keep reading lines until end of file // is reached. while(s.hasNextLine( )) { // Read next line in input file. String line = s.nextLine( ); // Call split to extract fields. String[ ] fields = line.split(","); // First field is name. String name = fields[0]; // Second field is gender char gender = fields[1].charAt(0); // Third field is age int age = Integer.parseInt(fields[2]); // Create Person object from fields Person p = new Person(name, gender, age); // Put Person object into array a[lineNumber] = p; // Increment line number lineNumber++; } // Print array of Person objects int numberOfLines = lineNumber; for(int i = 0; i < numberOfLines; i++) { System.out.println(a[i]); } } }