用java做一个通讯录
时间: 2023-10-12 07:10:55 浏览: 86
好的,以下是一个简单的通讯录的 Java 代码,你可以参考:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AddressBook {
private static Map<String, String> addressBook = new HashMap<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("\n请选择操作:");
System.out.println("1. 添加联系人");
System.out.println("2. 删除联系人");
System.out.println("3. 查找联系人");
System.out.println("4. 显示所有联系人");
System.out.println("5. 退出程序");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.print("请输入联系人姓名:");
String name = scanner.nextLine();
System.out.print("请输入联系人电话:");
String phone = scanner.nextLine();
addContact(name, phone);
break;
case 2:
System.out.print("请输入要删除的联系人姓名:");
String deleteName = scanner.nextLine();
deleteContact(deleteName);
break;
case 3:
System.out.print("请输入要查找的联系人姓名:");
String searchName = scanner.nextLine();
searchContact(searchName);
break;
case 4:
displayContacts();
break;
case 5:
running = false;
break;
default:
System.out.println("输入有误,请重新选择!");
}
}
System.out.println("程序已退出。");
}
private static void addContact(String name, String phone) {
if (addressBook.containsKey(name)) {
System.out.println("联系人已存在,添加失败!");
} else {
addressBook.put(name, phone);
System.out.println("联系人添加成功!");
}
}
private static void deleteContact(String name) {
if (addressBook.containsKey(name)) {
addressBook.remove(name);
System.out.println("联系人删除成功!");
} else {
System.out.println("联系人不存在,删除失败!");
}
}
private static void searchContact(String name) {
if (addressBook.containsKey(name)) {
System.out.printf("联系人姓名:%s,电话:%s\n", name, addressBook.get(name));
} else {
System.out.println("联系人不存在!");
}
}
private static void displayContacts() {
if (addressBook.isEmpty()) {
System.out.println("通讯录为空!");
} else {
System.out.println("所有联系人:");
for (String name : addressBook.keySet()) {
System.out.printf("联系人姓名:%s,电话:%s\n", name, addressBook.get(name));
}
}
}
}
```
这个通讯录程序使用了一个 `Map` 类型的数据结构 `addressBook` 来存储联系人信息,其中键为联系人姓名,值为联系人电话。通过 `Scanner` 类从用户输入中读取操作选择和联系人信息,调用相应的方法进行操作,如添加联系人、删除联系人、查找联系人和显示所有联系人。
阅读全文