假设你叫林大棉,你需要用JAVA程序写出通讯录
时间: 2024-02-20 14:01:58 浏览: 58
好的,我可以帮你编写一个基本的通讯录程序。这个程序可以实现添加联系人、查找联系人、删除联系人、显示所有联系人等基本功能。以下是程序的代码:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
private ArrayList<Contact> contacts;
public ContactList() {
contacts = new ArrayList<Contact>();
}
public void addContact(Contact c) {
contacts.add(c);
}
public void removeContact(Contact c) {
contacts.remove(c);
}
public void displayAllContacts() {
System.out.println("Contact List:");
for (Contact c : contacts) {
System.out.println(c);
}
}
public Contact findContact(String name) {
for (Contact c : contacts) {
if (c.getName().equals(name)) {
return c;
}
}
return null;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ContactList cl = new ContactList();
while (true) {
System.out.println("\nWhat would you like to do?");
System.out.println("1 - Add a contact");
System.out.println("2 - Remove a contact");
System.out.println("3 - Display all contacts");
System.out.println("4 - Find a contact");
System.out.println("5 - Quit");
int choice = input.nextInt();
input.nextLine();
switch (choice) {
case 1:
System.out.print("Enter name: ");
String name = input.nextLine();
System.out.print("Enter phone number: ");
String phone = input.nextLine();
System.out.print("Enter email: ");
String email = input.nextLine();
Contact c = new Contact(name, phone, email);
cl.addContact(c);
System.out.println("Contact added.");
break;
case 2:
System.out.print("Enter name: ");
String name2 = input.nextLine();
Contact c2 = cl.findContact(name2);
if (c2 != null) {
cl.removeContact(c2);
System.out.println("Contact removed.");
} else {
System.out.println("Contact not found.");
}
break;
case 3:
cl.displayAllContacts();
break;
case 4:
System.out.print("Enter name: ");
String name3 = input.nextLine();
Contact c3 = cl.findContact(name3);
if (c3 != null) {
System.out.println(c3);
} else {
System.out.println("Contact not found.");
}
break;
case 5:
System.out.println("Goodbye!");
System.exit(0);
default:
System.out.println("Invalid choice.");
break;
}
}
}
}
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;
}
public String toString() {
return name + " " + phone + " " + email;
}
}
```
希望能够帮助到你!
阅读全文