Reads Persons from a File 9 records found: 1. John Q. Daly 123-4567 2. Mary F. Hartman (213) 555-1212 3. Arthur C. Clark 987-1234 4. Mallory Z. Yolo 567-1234 5. Mallory Y. Yolo (321) 456-1234 6. John Q. Daily 999-3333 7. Marie D. Hartman (818) 555-2121 8. Arturo C. Clark (987) 123-6666 9. Arthur C. Clarke (345) 222-1111
ArrayList<Person> swap( ArrayList<Person> list, int a, int b)that returns a copy of the list, exchanging elements a and b. Use this to exchange the first and the last element so that it prints:
9 records found: 1. Arthur C. Clarke (345) 222-1111 2. Mary F. Hartman (213) 555-1212 3. Arthur C. Clark 987-1234 4. Mallory Z. Yolo 567-1234 5. Mallory Y. Yolo (321) 456-1234 6. John Q. Daily 999-3333 7. Marie D. Hartman (818) 555-2121 8. Arturo C. Clark (987) 123-6666 9. John Q. Daly 123-4567
ArrayList<Person> sortByLastName( ArrayList<Person> list){ return list; }This will sort the list, based upon the last name. You are free to use selection sort, insertion sort or merge sort.
ArrayList<Person> sortByFullName( ArrayList<Person> list)This will sort the list, based upon the full last name
John Q Daly;1234567 Mary F Hartman;2135551212 Arthur C Clark;9871234 Mallory Z Yolo;5671234 Mallory Y Yolo;3214561234 John Q Daily;9993333 Marie D Hartman;8185552121 Arturo C Clark;9871236666 Arthur C Clarke;3452221111
import java.io.*; import java.util.ArrayList; public class ReadPersonFile { public static void main (String args[]) throws IOException { ArrayList<Person> list = new ArrayList<Person>(); System.out.println("\nReads Persons from a File\n"); File inFile = new File("people.txt"); if (inFile.exists()) { BufferedReader inStream = new BufferedReader(new FileReader(inFile)); String inString; while((inString = inStream.readLine()) != null) { String[] next=inString.split(";"); // divide the line into 2 Strings String n=next[0]; //the first half is the name String p=next[1]; //the rest is the phone number list.add(new Person(n,p)); } inStream.close(); System.out.println("Unsorted"); for(Person p:list) System.out.println(p); System.out.println("Sorted by Last Name"); //list=sortByLastName(list); for(Person p:list) System.out.println(p); System.out.println("Sorted by Full Name"); //list=sortByFullName(list); for(Person p:list) System.out.println(p); } else { System.out.println("Specified file \"people.txt\" does not exist."); System.out.println("Program aborted."); } System.out.println(); } }