java手机通讯录代码
时间: 2023-09-18 11:02:27 浏览: 153
下面是一个用Java编写的手机通讯录代码示例:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class PhoneBook {
private static Map<String, String> phoneBook = new HashMap<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:");
System.out.println("1. 添加联系人");
System.out.println("2. 查找联系人");
System.out.println("3. 删除联系人");
System.out.println("4. 显示通讯录");
System.out.println("5. 退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
addContact(scanner);
break;
case 2:
findContact(scanner);
break;
case 3:
removeContact(scanner);
break;
case 4:
displayContacts();
break;
case 5:
System.out.println("已退出!");
return;
default:
System.out.println("无效的选择!");
}
}
}
private static void addContact(Scanner scanner) {
System.out.println("请输入姓名:");
String name = scanner.next();
System.out.println("请输入电话号码:");
String phoneNumber = scanner.next();
phoneBook.put(name, phoneNumber);
System.out.println("联系人已添加!");
}
private static void findContact(Scanner scanner) {
System.out.println("请输入要查找的姓名:");
String name = scanner.next();
String phoneNumber = phoneBook.get(name);
if (phoneNumber == null) {
System.out.println("未找到该联系人!");
} else {
System.out.println(name + " 的电话号码是:" + phoneNumber);
}
}
private static void removeContact(Scanner scanner) {
System.out.println("请输入要删除的联系人的姓名:");
String name = scanner.next();
String phoneNumber = phoneBook.get(name);
if (phoneNumber == null) {
System.out.println("未找到该联系人!");
} else {
phoneBook.remove(name);
System.out.println("联系人已删除!");
}
}
private static void displayContacts() {
System.out.println("通讯录内容:");
if (phoneBook.isEmpty()) {
System.out.println("通讯录为空!");
} else {
for (String name : phoneBook.keySet()) {
String phoneNumber = phoneBook.get(name);
System.out.println(name + ": " + phoneNumber);
}
}
}
}
```
这个代码使用了一个`HashMap`来存储联系人的姓名和电话号码,提供了添加联系人、查找联系人、删除联系人和显示通讯录的功能。用户可以根据提示分别选择需要的操作,在添加或查找联系人时输入姓名和电话号码,删除联系人时输入姓名即可。通讯录中的内容会实时显示给用户。
阅读全文