用java写一个通讯录管理代码
时间: 2024-03-18 12:42:23 浏览: 62
好的,以下是一个简单的通讯录管理代码示例:
```
import java.util.ArrayList;
import java.util.Scanner;
public class ContactManager {
private ArrayList<Contact> contacts;
public ContactManager() {
contacts = new ArrayList<>();
}
public void addContact(Contact contact) {
contacts.add(contact);
}
public void removeContact(Contact contact) {
contacts.remove(contact);
}
public void printContacts() {
for (Contact contact : contacts) {
System.out.println(contact);
}
}
public static void main(String[] args) {
ContactManager manager = new ContactManager();
Scanner input = new Scanner(System.in);
String name, phone, email;
int choice;
do {
System.out.println("1. Add contact");
System.out.println("2. Remove contact");
System.out.println("3. Print contacts");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
System.out.print("Enter name: ");
name = input.next();
System.out.print("Enter phone number: ");
phone = input.next();
System.out.print("Enter email: ");
email = input.next();
manager.addContact(new Contact(name, phone, email));
break;
case 2:
System.out.print("Enter name: ");
name = input.next();
for (Contact contact : manager.contacts) {
if (contact.getName().equals(name)) {
manager.removeContact(contact);
break;
}
}
break;
case 3:
manager.printContacts();
break;
case 4:
break;
default:
System.out.println("Invalid choice");
}
} while (choice != 4);
}
}
class Contact {
private String name;
private String phone;
private String email;
public Contact(String name, String phone, String email) {
this.name = name;
this.phone = phone;
this.email = email;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "Name: " + name + ", Phone: " + phone + ", Email: " + email;
}
}
```
这个程序可以让用户添加、删除和打印联系人信息。每个联系人都有一个名字、电话号码和电子邮件地址。用户可以输入选项来执行相应的操作。以上仅供参考,具体实现还需要根据需求进行修改和完善。
阅读全文