Java基础之集合框架——在文件中存储地图(TryPhoneBook2)
控制台程序。
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基础之集合框架——在文件中存储地图(TryPhoneBook2)的更多相关文章
- Java基础--说集合框架
版权所有,转载注明出处. 1,Java中,集合是什么?为什么会出现? 根据数学的定义,集合是一个元素或多个元素的构成,即集合一个装有元素的容器. Java中已经有数组这一装有元素的容器,为什么还要新建 ...
- 黑马程序员——【Java基础】——集合框架
---------- android培训.java培训.期待与您交流! ---------- 一.集合框架概述 (一)集合框架中集合类关系简化图 (二)为什么出现集合类? 面向对象语言对事物的体现都是 ...
- java基础37 集合框架工具类Collections和数组操作工具类Arrays
一.集合框架工具类:Collections 1.1.Collections类的特点 该工具类中所有的方法都是静态的 1.2.Collections类的常用方法 binarySearch(List< ...
- Thinking in java基础之集合框架(转载)
集合简介(容器)把具有相同性质的一类东西,汇聚成一个整体,就可以称为集合,例如这里有20个苹果,我们把每一个苹果当成一个东西(一个对象),然后我们借用袋子把这20个苹果装起来,而这个袋子就是集合(也叫 ...
- Java基础之集合框架(Collection接口和List接口)
首先我们说说集合有什么作用. 一.集合的作用 1.在类的内部,对数据进行组织: 2.简单而快速的搜索大数量的条目: 3.有的集合接口,提供一系列排列有序的元素,并且可以在序列中间快速的插入或者删除有关 ...
- java基础之集合框架
6.集合框架: (1)为什么出现集合类? 面向对象对事物的体现都是以对象的形式,为了方便对多个对象的操作,就对对象进行存储. 集合就是存储对象最常用的一种方式. (2)数组和集合都是容器,两者有何不同 ...
- Java基础之集合框架——使用集合Vector<>挑选演员(TryVector)
控制台程序. public class Person implements Comparable<Person> { // Constructor public Person(String ...
- Java导出List集合到txt文件中——(四)
有时候,需要将数据以一定格式导出到txt文件中.利用Java的IO可以轻松的导出数据到txt中. package Action.txt; import java.io.BufferedWriter; ...
- Java基础之集合框架——使用堆栈Stack<>对象模拟发牌(TryDeal)
控制台程序. public enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, A ...
随机推荐
- 使用webdriver + phantomjs + pdfkit 生成PDF文件
实例 #!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on Dec 6, 2013 @author: Jay <smile665@gm ...
- linux 自动登录脚本
#!/usr/bin/expect set port 22 set user xiaoming set password xiaoming123 set host 111.222.22.33 set ...
- linux面试题及答案
http://www.cnblogs.com/itech/archive/2011/02/12/1952857.html 一.填空题:1. 在Linux系统中,以 文件 方式访问设备 .2. Linu ...
- passing parameters by value is inefficient when the parameters represent large blocks of data
Computer Science An Overview _J. Glenn Brookshear _11th Edition_C Note that passing parameters by va ...
- 【转】Unity 解析Json字符串
http://blog.csdn.net/qq_15267341/article/details/52013190 LitJSON使用很简单,两个步骤: 1 将LitJSON.dll文件拖动到unit ...
- Python之 continue继续循环和多重循环
Python之 continue继续循环 在循环过程中,可以用break退出当前循环,还可以用continue跳过后续循环代码,继续下一次循环. 假设我们已经写好了利用for循环计算平均分的代码: L ...
- 文件对比工具Beyond Compare使用方法
今天向大家介绍一个使用起来十分方便且功能十分强大的文件对比工具-Beyond Compare. 1 工具下载 工具的下载很简单,百度搜索Beyond Compare即可. 下载完成后,解压缩,双 ...
- 为mutable类型的容器(array,set等)添加kvo,有点麻烦,供参考和了解下吧
http://blog.csdn.net/caryaliu/article/details/49284185 需要在被观察的属性所在的类里面实现一些方法,对开发者不友好,一般不建议使用,这里mark一 ...
- php-- Linux图形界面与字符界面切换
转自:http://blog.163.com/wang_ly2442/blog/static/9494340720128355054551/ 1. 启动时进入字符界面,后来想切换到图形界面:使用sta ...
- Eclipse 常用整理
1.编译 eclipse默认是修改程序后自动编译的,如果不能自动编译,你可以查看project->build automatically选项是否被选中. 手动编译整个工程,可以使用Project ...