zoukankan      html  css  js  c++  java
  • Java基础之集合框架——在文件中存储地图(TryPhoneBook2)

    控制台程序。

     1 import java.io.*;
     2 
     3 public class Person implements Comparable<Person>, Serializable {
     4   // Constructor
     5   public Person(String firstName, String surname) {
     6     this.firstName = firstName;
     7     this.surname = surname;
     8   }
     9 
    10   // Read a person from the keyboard
    11   public static Person readPerson() {
    12     String firstName = null;
    13     String surname = null;
    14     try {
    15       System.out.print("Enter first name: ");
    16       firstName = keyboard.readLine().trim();
    17       System.out.print("Enter surname: ");
    18       surname = keyboard.readLine().trim();
    19     } catch(IOException e) {
    20       System.err.println("Error reading a name.");
    21       e.printStackTrace();
    22       System.exit(1);
    23     }
    24     return new Person(firstName,surname);
    25   }
    26 
    27   @Override
    28   public boolean equals(Object person) {
    29     return compareTo((Person)person) == 0;
    30   }
    31 
    32   @Override
    33   public int hashCode() {
    34     return 7*firstName.hashCode()+13*surname.hashCode();
    35   }
    36 
    37   @Override
    38   public String toString() {
    39     return firstName + " " + surname;
    40   }
    41 
    42   // Compare Person objects
    43   public int compareTo(Person person) {
    44     int result = surname.compareTo(person.surname);
    45     return result == 0 ? firstName.compareTo(person.firstName) : result;
    46   }
    47 
    48   private String firstName;                                            // First name of person
    49   private String surname;                                              // Second name of person
    50   private static final long serialVersionUID = 1001L;
    51   private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    52 }
     1 import java.io.*;
     2 
     3 class PhoneNumber implements Serializable {
     4   public PhoneNumber(String areacode, String number) {
     5     this.areacode = areacode;
     6     this.number = number;
     7   }
     8 
     9   // Read a phone number from the keyboard
    10   public static PhoneNumber readNumber() {
    11     String area = null;                                                // Stores the area code
    12     String localcode = null;                                           // Stores the local code
    13     try {
    14       System.out.print("Enter area code: ");
    15       area = keyboard.readLine().trim();
    16       System.out.print("Enter local code: ");
    17       localcode = keyboard.readLine().trim();
    18       System.out.print("Enter the number: ");
    19       localcode += " " + keyboard.readLine().trim();
    20     } catch(IOException e) {
    21       System.err.println("Error reading a phone number.");
    22       e.printStackTrace();
    23       System.exit(1);
    24     }
    25     return new PhoneNumber(area,localcode);
    26   }
    27 
    28   @Override
    29   public String toString() {
    30     return areacode + " " + number;
    31   }
    32 
    33   private String areacode;
    34   private String number;
    35   private static final long serialVersionUID = 1001L;
    36   private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    37 }
     1 import java.io.Serializable;
     2 
     3 class BookEntry implements Comparable<BookEntry>, Serializable {
     4   public int compareTo(BookEntry entry) {
     5     return person.compareTo(entry.getPerson());
     6   }
     7 
     8   public BookEntry(Person person, PhoneNumber number) {
     9    this.person = person;
    10     this.number = number;
    11   }
    12 
    13   public Person getPerson() {
    14     return person;
    15   }
    16 
    17   public PhoneNumber getNumber() {
    18     return number;
    19   }
    20 
    21   @Override
    22   public String toString() {
    23     return person.toString() + '
    ' + number.toString();
    24   }
    25 
    26   // Read an entry from the keyboard
    27   public static BookEntry readEntry() {
    28     return new BookEntry(Person.readPerson(), PhoneNumber.readNumber());
    29   }
    30 
    31   private Person person;
    32   private PhoneNumber number;
    33   private static final long serialVersionUID = 1001L;
    34 }
     1 import java.nio.file.*;
     2 import java.io.*;
     3 import java.util.*;
     4 
     5 class PhoneBook implements Serializable {
     6   // List all entries in the book
     7   public void listEntries() {
     8     // Get the entries as a linked list
     9     LinkedList<BookEntry> entries = new LinkedList<>(phonebook.values());
    10     Collections.sort(entries);                                         // Sort the entries
    11 
    12     for(BookEntry entry : entries) {
    13       System.out.println(entry);
    14     }
    15   }
    16   @SuppressWarnings("unchecked")
    17   public PhoneBook() {
    18     if(Files.exists(file)) {                                           // If there's a phone book in a file...
    19       try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(file)))){
    20         phonebook = (HashMap<Person, BookEntry>)in.readObject();       //...read it in.
    21       } catch(ClassNotFoundException| IOException e) {
    22         e.printStackTrace();
    23         System.exit(1);
    24       }
    25     }
    26   }
    27 
    28   public void save() {
    29     try {
    30       Files.createDirectories(file.getParent());                       // Make sure we have the directory
    31     } catch (IOException e) {
    32       System.err.println("I/O error creating directory. " + e.getMessage());
    33       e.printStackTrace();
    34       System.exit(1);
    35     }
    36     try (ObjectOutputStream out = new ObjectOutputStream(
    37                     new BufferedOutputStream(Files.newOutputStream(file)))){
    38       System.out.println("Saving phone book");
    39       out.writeObject(phonebook);
    40       System.out.println("Done");
    41     } catch(IOException e) {
    42       System.out.println("I/O error saving phone book. " + e.getMessage());
    43       e.printStackTrace();
    44       System.exit(1);
    45     }
    46   }
    47 
    48   public void addEntry(BookEntry entry) {
    49     phonebook.put(entry.getPerson(), entry);
    50   }
    51 
    52   public BookEntry getEntry(Person key) {
    53     return phonebook.get(key);
    54   }
    55 
    56   public PhoneNumber getNumber(Person key) {
    57     BookEntry entry = getEntry(key);
    58     if(entry != null) {
    59     return entry.getNumber();
    60     } else {
    61       return null;
    62     }
    63   }
    64 
    65   private HashMap<Person,BookEntry> phonebook = new HashMap<>();
    66   private static final long serialVersionUID = 1001L;
    67   private Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Phonebook.bin");
    68 }
     1 import java.io.StreamTokenizer;
     2 import java.io.BufferedReader;
     3 import java.io.InputStreamReader;
     4 import java.io.IOException;
     5 
     6 public class FormattedInput {
     7 
     8   public int readInt() throws InvalidUserInputException {
     9     if (readToken() != StreamTokenizer.TT_NUMBER) {
    10       throw new InvalidUserInputException("readInt() failed." + "Input data not numeric");
    11     }
    12 
    13     if (tokenizer.nval > (double) Integer.MAX_VALUE || tokenizer.nval < (double) Integer.MIN_VALUE) {
    14       throw new InvalidUserInputException("readInt() failed." + "Input outside range of type int");
    15     }
    16 
    17     if (tokenizer.nval != (double) (int) tokenizer.nval) {
    18       throw new InvalidUserInputException("readInt() failed." + "Input not an integer");
    19     }
    20     return (int) tokenizer.nval;
    21   }
    22 
    23   public double readDouble() throws InvalidUserInputException {
    24     if (readToken() != StreamTokenizer.TT_NUMBER) {
    25       throw new InvalidUserInputException("readDouble() failed." + "Input data not numeric");
    26     }
    27     return tokenizer.nval;
    28   }
    29 
    30   public String readString() throws InvalidUserInputException {
    31     if (readToken() == StreamTokenizer.TT_WORD || ttype == '"' || ttype == '"') {
    32       return tokenizer.sval;
    33     } else {
    34       throw new InvalidUserInputException("readString() failed." + "Input data is not a string");
    35     }
    36   }
    37   // Plus methods to read various other data types...
    38 
    39   // Helper method to read the next token
    40   private int readToken() {
    41     try {
    42       ttype = tokenizer.nextToken();
    43       return ttype;
    44 
    45     } catch (IOException e) {                                          // Error reading in nextToken()
    46       e.printStackTrace();
    47       System.exit(1);                                                  // End the program
    48     }
    49     return 0;
    50   }
    51 
    52   // Object to tokenize input from the standard input stream
    53   private StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    54   private int ttype;                                                   // Stores the token type code
    55 }
     1 public class InvalidUserInputException extends Exception {
     2   public InvalidUserInputException() {  }
     3 
     4   public InvalidUserInputException(String message) {
     5     super(message);
     6   }
     7 
     8   private static final long serialVersionUID = 9876L;
     9 
    10 }
     1 public class TryPhoneBook2 {
     2   public static void main(String[] args) {
     3     PhoneBook book = new PhoneBook();                                  // The phone book
     4     FormattedInput in = new FormattedInput();                          // Keyboard input
     5     Person someone;
     6     while(true) {
     7       System.out.println("Enter 1 to enter a new phone book entry
    "+
     8                          "Enter 2 to find the number for a name
    "+
     9                          "Enter 3 to list all the entries
    " +
    10                          "Enter 9 to quit.");
    11       int what = 0;                                                    // Stores input selection
    12       try {
    13         what = in.readInt();
    14 
    15       } catch(InvalidUserInputException e) {
    16         System.out.println(e.getMessage()+"
    Try again.");
    17         continue;
    18       }
    19 
    20       switch(what) {
    21         case 1:
    22           book.addEntry(BookEntry.readEntry());
    23           break;
    24         case 2:
    25           someone = Person.readPerson();
    26           BookEntry entry = book.getEntry(someone);
    27           if(entry == null) {
    28             System.out.println("The number for " + someone + " was not found.");
    29           } else {
    30             System.out.println("The number for " + someone + " is " + entry.getNumber());
    31           }
    32           break;
    33         case 3:
    34           book.listEntries();
    35           break;
    36         case 9:
    37           book.save();
    38           System.out.println("Ending program.");
    39           return;
    40         default:
    41           System.out.println("Invalid selection, try again.");
    42           break;
    43       }
    44     }
    45   }
    46 }
  • 相关阅读:
    python全栈开发_day48_bootstrap
    python全栈开发_day47_js,jQuery
    python全栈开发_day46_html文本标签
    抽象集合
    ViewState的用法
    sql(join中on与where区别)
    微软的技术文档链接地址
    微软的帮助文档,详细的介绍VS开发工具的使用
    [摘录]解决C# DateTime去掉时分秒几种方法
    验证(摘录)
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3430485.html
Copyright © 2011-2022 走看看