Java基础之集合框架——在文件中存储地图(TryPhoneBook2)
2013-11-18 23:11
405 查看
控制台程序。
import java.io.*; public class Person implements Comparable<Person>, Serializable { // Constructor public Person(String firstName, String surname) { this.firstName = firstName; this.surname = surname; } // Read a person from the keyboard public static Person readPerson() { String firstName = null; String surname = null; try { System.out.print("Enter first name: "); firstName = keyboard.readLine().trim(); System.out.print("Enter surname: "); surname = keyboard.readLine().trim(); } catch(IOException e) { System.err.println("Error reading a name."); e.printStackTrace(); System.exit(1); } return new Person(firstName,surname); } @Override public boolean equals(Object person) { return compareTo((Person)person) == 0; } @Override public int hashCode() { return 7*firstName.hashCode()+13*surname.hashCode(); } @Override public String toString() { return firstName + " " + surname; } // Compare Person objects public int compareTo(Person person) { int result = surname.compareTo(person.surname); return result == 0 ? firstName.compareTo(person.firstName) : result; } private String firstName; // First name of person private String surname; // Second name of person private static final long serialVersionUID = 1001L; private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); }
import java.io.*; class PhoneNumber implements Serializable { public PhoneNumber(String areacode, String number) { this.areacode = areacode; this.number = number; } // Read a phone number from the keyboard public static PhoneNumber readNumber() { String area = null; // Stores the area code String localcode = null; // Stores the local code try { System.out.print("Enter area code: "); area = keyboard.readLine().trim(); System.out.print("Enter local code: "); localcode = keyboard.readLine().trim(); System.out.print("Enter the number: "); localcode += " " + keyboard.readLine().trim(); } catch(IOException e) { System.err.println("Error reading a phone number."); e.printStackTrace(); System.exit(1); } return new PhoneNumber(area,localcode); } @Override public String toString() { return areacode + " " + number; } private String areacode; private String number; private static final long serialVersionUID = 1001L; private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); }
import java.io.Serializable; class BookEntry implements Comparable<BookEntry>, Serializable { public int compareTo(BookEntry entry) { return person.compareTo(entry.getPerson()); } public BookEntry(Person person, PhoneNumber number) { this.person = person; this.number = number; } public Person getPerson() { return person; } public PhoneNumber getNumber() { return number; } @Override public String toString() { return person.toString() + '\n' + number.toString(); } // Read an entry from the keyboard public static BookEntry readEntry() { return new BookEntry(Person.readPerson(), PhoneNumber.readNumber()); } private Person person; private PhoneNumber number; private static final long serialVersionUID = 1001L; }
import java.nio.file.*; import java.io.*; import java.util.*; class PhoneBook implements Serializable { // List all entries in the book public void listEntries() { // Get the entries as a linked list LinkedList<BookEntry> entries = new LinkedList<>(phonebook.values()); Collections.sort(entries); // Sort the entries for(BookEntry entry : entries) { System.out.println(entry); } } @SuppressWarnings("unchecked") public PhoneBook() { if(Files.exists(file)) { // If there's a phone book in a file... try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(file)))){ phonebook = (HashMap<Person, BookEntry>)in.readObject(); //...read it in. } catch(ClassNotFoundException| IOException e) { e.printStackTrace(); System.exit(1); } } } public void save() { try { Files.createDirectories(file.getParent()); // Make sure we have the directory } catch (IOException e) { System.err.println("I/O error creating directory. " + e.getMessage()); e.printStackTrace(); System.exit(1); } try (ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream(Files.newOutputStream(file)))){ System.out.println("Saving phone book"); out.writeObject(phonebook); System.out.println("Done"); } catch(IOException e) { System.out.println("I/O error saving phone book. " + e.getMessage()); e.printStackTrace(); System.exit(1); } } public void addEntry(BookEntry entry) { phonebook.put(entry.getPerson(), entry); } public BookEntry getEntry(Person key) { return phonebook.get(key); } public PhoneNumber getNumber(Person key) { BookEntry entry = getEntry(key); if(entry != null) { return entry.getNumber(); } else { return null; } } private HashMap<Person,BookEntry> phonebook = new HashMap<>(); private static final long serialVersionUID = 1001L; private Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Phonebook.bin"); }
import java.io.StreamTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class FormattedInput { public int readInt() throws InvalidUserInputException { if (readToken() != StreamTokenizer.TT_NUMBER) { throw new InvalidUserInputException("readInt() failed." + "Input data not numeric"); } if (tokenizer.nval > (double) Integer.MAX_VALUE || tokenizer.nval < (double) Integer.MIN_VALUE) { throw new InvalidUserInputException("readInt() failed." + "Input outside range of type int"); } if (tokenizer.nval != (double) (int) tokenizer.nval) { throw new InvalidUserInputException("readInt() failed." + "Input not an integer"); } return (int) tokenizer.nval; } public double readDouble() throws InvalidUserInputException { if (readToken() != StreamTokenizer.TT_NUMBER) { throw new InvalidUserInputException("readDouble() failed." + "Input data not numeric"); } return tokenizer.nval; } public String readString() throws InvalidUserInputException { if (readToken() == StreamTokenizer.TT_WORD || ttype == '\"' || ttype == '\"') { return tokenizer.sval; } else { throw new InvalidUserInputException("readString() failed." + "Input data is not a string"); } } // Plus methods to read various other data types... // Helper method to read the next token private int readToken() { try { ttype = tokenizer.nextToken(); return ttype; } catch (IOException e) { // Error reading in nextToken() e.printStackTrace(); System.exit(1); // End the program } return 0; } // Object to tokenize input from the standard input stream private StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); private int ttype; // Stores the token type code }
public class InvalidUserInputException extends Exception { public InvalidUserInputException() { } public InvalidUserInputException(String message) { super(message); } private static final long serialVersionUID = 9876L; }
public class TryPhoneBook2 { public static void main(String[] args) { PhoneBook book = new PhoneBook(); // The phone book FormattedInput in = new FormattedInput(); // Keyboard input Person someone; while(true) { System.out.println("Enter 1 to enter a new phone book entry\n"+ "Enter 2 to find the number for a name\n"+ "Enter 3 to list all the entries\n" + "Enter 9 to quit."); int what = 0; // Stores input selection try { what = in.readInt(); } catch(InvalidUserInputException e) { System.out.println(e.getMessage()+"\nTry again."); continue; } switch(what) { case 1: book.addEntry(BookEntry.readEntry()); break; case 2: someone = Person.readPerson(); BookEntry entry = book.getEntry(someone); if(entry == null) { System.out.println("The number for " + someone + " was not found."); } else { System.out.println("The number for " + someone + " is " + entry.getNumber()); } break; case 3: book.listEntries(); break; case 9: book.save(); System.out.println("Ending program."); return; default: System.out.println("Invalid selection, try again."); break; } } } }
相关文章推荐
- Java基础之集合框架——使用HashMap地图(TryPhoneBook1)
- Java基础知识强化之集合框架笔记12:Collection集合存储字符串并遍历
- Java基础知识强化之集合框架笔记13:Collection集合存储学生对象并遍历
- Java基础知识强化之集合框架笔记14:List集合存储字符串并遍历
- Java基础知识强化之集合框架笔记69:Collections类之ArrayList存储自自定义对象并排序的案例
- Java基础知识强化之集合框架笔记06:Collection集合存储自定义对象并遍历的案例
- Java基础知识强化之集合框架笔记45:Set集合之TreeSet存储自定义对象并遍历练习1(自然排序)
- 【java基础:集合和IO】文件深度遍历和存储的demostration
- Java基础知识强化之集合框架笔记39:Set集合之HashSet存储字符串并遍历
- Java基础知识强化之集合框架笔记23:ArrayList存储字符串并遍历
- Java基础知识强化之集合框架笔记43:Set集合之TreeSet存储Integer类型的元素并遍历
- Java基础知识强化之集合框架笔记40:Set集合之HashSet存储自定义对象并遍历
- Java基础知识强化之集合框架笔记24:ArrayList存储自定义对象并遍历
- Java基础知识强化之集合框架笔记41:Set集合之HashSet存储自定义对象并遍历练习
- Java基础知识强化之集合框架笔记46:Set集合之TreeSet存储自定义对象并遍历练习2(自然排序)
- java基础-- 集合框架入门 及 List集合
- 黑马程序员——【Java基础】——集合框架
- Java基础2——集合框架
- 黑马程序员——Java重点基础之集合框架(二)
- Java基础-集合框架之List