另一个 Java 实验通讯录管理程序

特点:

  • 命令行菜单式操作
  • 批量添加联系人
  • 添加、查询、修改、删除联系人
  • 列出、搜索联系人
  • 保存、载入数据文件

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.darwindev;
import java.util.Scanner;
public class Main {
private static void displayMenu() {
System.out.println(
"@ 1. Patch Add Contacts" + "\n" +
"@ 2. Add Contact" + "\n" +
"@ 3. Query Contact" + "\n" +
"@ 4. Edit Contact" + "\n" +
"@ 5. Delete Contact" + "\n" +
"@ 6. List All Contacts" + "\n" +
"@ 7. Filter Contacts" + "\n" +
"@ S. Save Contacts" + "\n" +
"@ R. Read Contacts" + "\n" +
"@ E. Exit"
);
}
public static void main(String[] args) {
System.out.println("FF Contact Service v1.0");
displayMenu();
while (true) {
Scanner reader = new Scanner(System.in);
System.out.print(FFContactService.sharedInstance().filename + (FFContactService.sharedInstance().edited ? " # " : " $ "));
String choice = reader.nextLine().toUpperCase();
switch (choice) {
case "1":
FFContactService.sharedInstance().patchAddContacts();
break;
case "2":
FFContactService.sharedInstance().addContact();
break;
case "3":
FFContactService.sharedInstance().queryContact();
break;
case "4":
FFContactService.sharedInstance().editContact();
break;
case "5":
FFContactService.sharedInstance().deleteContact();
break;
case "6":
FFContactService.sharedInstance().listAllContacts();
break;
case "7":
FFContactService.sharedInstance().filterContacts();
break;
case "S":
FFContactService.sharedInstance().saveContacts();
break;
case "R":
FFContactService.sharedInstance().readContacts();
break;
case "E":
if (FFContactService.sharedInstance().edited) {
System.out.print("> Quit without saving (Y/N): ");
String exitFlag = reader.nextLine().toUpperCase();
if (exitFlag.equals("Y")) {
System.exit(0);
}
} else {
System.exit(0);
}
break;
default:
System.out.println("! Invalid Choice");
displayMenu();
break;
}
}
}
}

FFContactService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package com.darwindev;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
class FFContactService {
private ArrayList<FFContactModel> contacts = null;
private int num = 0;
String filename = "Untitled";
boolean edited = false;
private FFContactService() {
contacts = new ArrayList<>();
}
private static final FFContactService sharedInstance = new FFContactService();
static FFContactService sharedInstance () {
return sharedInstance;
}
void patchAddContacts() {
System.out.println("[Patch Add Contacts]");
try {
Scanner reader = new Scanner(System.in);
System.out.print(" > Num (0 for infinite): ");
int num = Integer.parseInt(reader.nextLine());
if (num == 0) {
num = Integer.MAX_VALUE;
}
for (int i = 0; i < num; i++) {
if (!addContact()) {
break;
}
}
} catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
boolean addContact() {
System.out.println("[Add Contact]");
try {
FFContactModel aContact = new FFContactModel();
Scanner reader = new Scanner(System.in);
int newId = num + 1;
aContact.setId(newId);
System.out.print("> Name: ");
String newName = reader.nextLine();
if (newName.length() == 0) {
return false;
}
aContact.setName(newName);
System.out.print("> Gender (M - Male, F - Female): ");
String newGenderStr = reader.nextLine();
if (newGenderStr.length() == 0) {
aContact.setGender(0);
} else {
aContact.setGenderString(newGenderStr);
}
System.out.print("> Mobile: ");
String newMobile = reader.nextLine();
aContact.setMobile(newMobile);
contacts.add(aContact);
num++;
edited = true;
System.out.println("= Created contact (" + Integer.toString(newId) + ")");
} catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
return true;
}
void deleteContact() {
System.out.println("[Delete Contact]");
try {
boolean find = false;
Scanner reader = new Scanner(System.in);
System.out.print("> Id to be deleted: ");
int oldId = Integer.parseInt(reader.nextLine());
FFContactModel aContact = null;
for (FFContactModel model:
contacts) {
if (model.id() == oldId) {
find = true;
aContact = model;
}
}
if (!find) {
throw new Exception("Cannot find contact at index (" + Integer.toString(oldId) + ")");
} else {
contacts.remove(aContact);
num--;
edited = true;
System.out.println("= Deleted contact (" + Integer.toString(oldId) + ")");
}
} catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
void editContact() {
System.out.println("[Edit Contact]");
try {
boolean find = false;
Scanner reader = new Scanner(System.in);
System.out.print("> Id to be edited: ");
int oldId = Integer.parseInt(reader.nextLine());
FFContactModel aContact = null;
for (FFContactModel model:
contacts) {
if (model.id() == oldId) {
find = true;
aContact = model;
}
}
if (!find) {
throw new Exception("Cannot find contact at index (" + Integer.toString(oldId) + ")");
} else {
System.out.print("> New name (" + aContact.name() + "): ");
String newName = reader.nextLine();
if (newName.length() != 0) {
aContact.setName(newName);
}
System.out.print("> New gender (" + aContact.genderString() + "): ");
String newGenderStr = reader.nextLine();
if (newGenderStr.length() != 0) {
aContact.setGenderString(newGenderStr);
}
System.out.print("> New mobile (" + aContact.mobile() + "): ");
String newMobile = reader.nextLine();
if (newMobile.length() != 0) {
aContact.setMobile(newMobile);
}
edited = true;
System.out.println("= Edited contact (" + Integer.toString(oldId) + ")");
}
} catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
void queryContact() {
System.out.println("[Query Contact]");
try {
boolean find = false;
Scanner reader = new Scanner(System.in);
System.out.print("> Id to be queried: ");
int oldId = Integer.parseInt(reader.nextLine());
FFContactModel aContact = null;
for (FFContactModel model:
contacts) {
if (model.id() == oldId) {
find = true;
aContact = model;
}
}
if (!find) {
throw new Exception("Cannot find contact at index (" + Integer.toString(oldId) + ")");
} else {
System.out.println(aContact.description());
}
} catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
void listAllContacts() {
System.out.println("[List All Contacts]");
System.out.println(FFContactModel.columnTitleDescription(true));
for (FFContactModel model:
contacts) {
System.out.println(model.shortDescription(true));
}
System.out.println("= Total: " + Integer.toString(num));
}
void filterContacts() {
System.out.println("[Filter Contacts]");
try {
boolean find = false;
Scanner reader = new Scanner(System.in);
System.out.println("= Available columns: " + FFContactModel.columnTitleDescription(false));
System.out.print("> Column to be filtered: ");
String columnString = reader.nextLine();
for (String column:
FFContactModel.columnTitles()) {
if (columnString.equals(column)) {
find = true;
}
}
if (!find) {
throw new Exception("Invalid column!");
}
int count = 0;
columnString = columnString.toLowerCase();
switch (columnString) {
case "id":
throw new Exception("Use \"Query Contact\" instead of \"Filter Contacts\"");
case "name":
System.out.print("> Search name: ");
String findName = reader.nextLine();
findName = findName.toLowerCase();
System.out.println(FFContactModel.columnTitleDescription(true));
for (FFContactModel model :
contacts) {
if (model.name().toLowerCase().contains(findName)) {
count++;
System.out.println(model.shortDescription(true));
}
}
break;
case "gender":
System.out.print("> Search gender: ");
int findGender = 0;
String findGenderStr = reader.nextLine();
findGenderStr = findGenderStr.toLowerCase().substring(0, 1);
if (findGenderStr.equals("m")) {
findGender = 1;
} else if (findGenderStr.equals("f")) {
findGender = 0;
}
System.out.println(FFContactModel.columnTitleDescription(true));
for (FFContactModel model :
contacts) {
if (model.gender() == findGender) {
count++;
System.out.println(model.shortDescription(true));
}
}
break;
case "mobile":
System.out.print("> Search mobile: ");
String findMobile = reader.nextLine();
findMobile = findMobile.toLowerCase();
System.out.println(FFContactModel.columnTitleDescription(true));
for (FFContactModel model :
contacts) {
if (model.mobile().toLowerCase().contains(findMobile)) {
count++;
System.out.println(model.shortDescription(true));
}
}
break;
}
System.out.println("= Filtered: " + Integer.toString(count));
} catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
void saveContacts() {
try {
Scanner reader = new Scanner(System.in);
System.out.print("> Save as (" + filename + "): ");
String tFilename = reader.nextLine();
if (tFilename.length() != 0) {
if (tFilename.matches("^[0-9a-zA-Z|_\\-]+$")) {
filename = tFilename;
} else {
throw new Exception("Invalid filename!");
}
}
File myFilePath = new File(filename);
if (!myFilePath.exists()) {
if (!myFilePath.createNewFile()) {
return;
}
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(num);
for (FFContactModel model:
contacts) {
myFile.println(model.shortDescription(false));
}
resultFile.close();
edited = false;
System.out.println("= File \"" + filename + "\" has been saved!");
}
catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
void readContacts() {
try {
Scanner reader = new Scanner(System.in);
System.out.print("> Read file (" + filename + "): ");
String tFilename = reader.nextLine();
if (tFilename.length() != 0) {
if (tFilename.matches("^[0-9a-zA-Z|_\\-]+$")) {
filename = tFilename;
} else {
throw new Exception("Invalid filename!");
}
}
File myFilePath = new File(filename);
if (!myFilePath.exists()) {
throw new Exception("File \"" + filename + "\" does not exist!");
}
FileReader resultFile = new FileReader(myFilePath);
BufferedReader fileReader = new BufferedReader(resultFile);
String numStr = fileReader.readLine();
int totalNum = Integer.parseInt(numStr);
contacts.clear();
for (int i = 0; i < totalNum; i++) {
String line;
FFContactModel aContact = new FFContactModel();
line = fileReader.readLine();
aContact.setId(Integer.parseInt(line));
line = fileReader.readLine();
aContact.setName(line);
line = fileReader.readLine();
aContact.setGenderString(line);
line = fileReader.readLine();
aContact.setMobile(line);
contacts.add(aContact);
num++;
}
resultFile.close();
edited = false;
System.out.println("= File \"" + filename + "\" loaded.");
}
catch (Exception e) {
System.out.println("! " + e.getMessage());
e.printStackTrace();
}
}
}

FFContactModel.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.darwindev;
class FFContactModel {
private int id = 0;
private String name = "";
private int gender = 0; // 0 - Female, 1 - Male
private String mobile = "";
// Getter
int id() {
return id;
}
String name() {
return name;
}
int gender() {
return gender;
}
String mobile() {
return mobile;
}
String genderString() {
if (gender == 0) {
return "Female";
} else if (gender == 1) {
return "Male";
}
return "Unknown";
}
// Setter & Validator
void setId(int i) {
id = i;
}
void setName(String n) throws Exception {
if (n.matches("^[a-zA-Z\\u4e00-\\u9fa5| ]+$")) { // Judge if they are Chinese characters or alphabets/whitespaces
name = n;
} else {
throw new Exception("Invalid name!");
}
}
void setGender(int g) throws Exception {
if (g == 0 || g == 1) { // Judge if gender is 0 or 1
gender = g;
} else {
throw new Exception("Invalid gender!");
}
}
void setGenderString(String gs) throws Exception {
switch (gs) {
case "M":
case "Male":
gender = 1;
break;
case "F":
case "Female":
gender = 0;
break;
default:
throw new Exception("Invalid gender string!");
}
}
void setMobile(String m) throws Exception {
if (m.matches("^[0-9]{11}$")) { // Judge if mobile is numeric and its length is 11
mobile = m;
} else {
throw new Exception("Invalid mobile!");
}
}
// Description
String description() {
return (
"= Id: " + Integer.toString(id) + "\n" +
"= Name: " + name + "\n" +
"= Gender: " + genderString() + "\n" +
"= Mobile: " + mobile
);
}
String shortDescription(boolean isTable) {
return ( isTable ?
String.format(
"%6s %24s %8s %13s",
Integer.toString(id),
name,
genderString(),
mobile) :
String.format(
"%s\n%s\n%s\n%s",
Integer.toString(id),
name,
genderString(),
mobile)
);
}
static String columnTitleDescription(boolean isTable) {
return ( isTable ?
String.format(
"%6s %24s %8s %13s",
"Id",
"Name",
"Gender",
"Mobile") :
String.format(
"%s, %s, %s, %s",
"Id",
"Name",
"Gender",
"Mobile")
);
}
static String[] columnTitles() {
return new String[] {
"Id", "Name", "Gender", "Mobile"
};
}
}
// This is the data model of any "Contact" instance.