用java生成一个通讯录
时间: 2024-02-20 18:59:47 浏览: 21
以下是一个简单的通讯录应用程序,使用 Java 编写:
```
import java.util.*;
public class Contacts {
private String name;
private String phoneNumber;
private String email;
public Contacts(String name, String phoneNumber, String email) {
this.name = name;
this.phoneNumber = phoneNumber;
this.email = email;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEmail() {
return email;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Contacts> contacts = new ArrayList<>();
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 = input.nextInt();
if (choice == 1) {
System.out.print("请输入联系人姓名:");
String name = input.next();
System.out.print("请输入联系人电话号码:");
String phoneNumber = input.next();
System.out.print("请输入联系人电子邮件:");
String email = input.next();
Contacts newContact = new Contacts(name, phoneNumber, email);
contacts.add(newContact);
System.out.println("联系人添加成功。");
} else if (choice == 2) {
System.out.print("请输入要查找的联系人姓名:");
String name = input.next();
boolean found = false;
for (Contacts contact : contacts) {
if (contact.getName().equals(name)) {
System.out.println("联系人姓名:" + contact.getName());
System.out.println("联系人电话号码:" + contact.getPhoneNumber());
System.out.println("联系人电子邮件:" + contact.getEmail());
found = true;
break;
}
}
if (!found) {
System.out.println("未找到该联系人。");
}
} else if (choice == 3) {
System.out.print("请输入要删除的联系人姓名:");
String name = input.next();
boolean removed = false;
Iterator<Contacts> iterator = contacts.iterator();
while (iterator.hasNext()) {
Contacts contact = iterator.next();
if (contact.getName().equals(name)) {
iterator.remove();
removed = true;
break;
}
}
if (removed) {
System.out.println("联系人删除成功。");
} else {
System.out.println("未找到该联系人。");
}
} else if (choice == 4) {
if (contacts.isEmpty()) {
System.out.println("通讯录中没有联系人。");
} else {
System.out.println("通讯录中所有联系人:");
for (Contacts contact : contacts) {
System.out.println("联系人姓名:" + contact.getName());
System.out.println("联系人电话号码:" + contact.getPhoneNumber());
System.out.println("联系人电子邮件:" + contact.getEmail());
System.out.println();
}
}
} else if (choice == 5) {
System.out.println("程序已退出。");
break;
} else {
System.out.println("无效的操作,请重新选择。");
}
}
}
}
```
以上的程序使用了 ArrayList 来存储联系人信息,并提供了添加、查找、删除和显示所有联系人的功能。用户可以通过控制台输入进行操作,程序会根据用户的选择执行相应的操作。