(1)创建一个小型通讯录,定义Friend类,具有属性:姓名、电话、邮箱和单位名称,用toString()方法显示其信息。 (2)编写测试类AddFriend,实现添加联系人的功能。
时间: 2023-05-27 09:07:32 浏览: 58
(1)Friend类的代码如下:
public class Friend {
private String name;
private String phoneNum;
private String email;
private String companyName;
public Friend(String name, String phoneNum, String email, String companyName) {
this.name = name;
this.phoneNum = phoneNum;
this.email = email;
this.companyName = companyName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String toString() {
return "Name: " + name + ", Phone Number: " + phoneNum + ", Email: " + email + ", Company Name: " + companyName;
}
}
(2)AddFriend测试类的代码如下:
import java.util.ArrayList;
import java.util.Scanner;
public class AddFriend {
public static void main(String[] args) {
ArrayList<Friend> friends = new ArrayList<Friend>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Please enter the name of your friend (or 'quit' to exit): ");
String name = scanner.nextLine();
if (name.equals("quit")) {
break;
}
System.out.println("Please enter the phone number of your friend: ");
String phoneNum = scanner.nextLine();
System.out.println("Please enter the email of your friend: ");
String email = scanner.nextLine();
System.out.println("Please enter the company name of your friend: ");
String companyName = scanner.nextLine();
Friend friend = new Friend(name, phoneNum, email, companyName);
friends.add(friend);
System.out.println("Your friend has been added to the address book.");
}
System.out.println("Your address book contains the following friends: ");
for (Friend friend : friends) {
System.out.println(friend.toString());
}
}
}
运行结果如下:
Please enter the name of your friend (or 'quit' to exit):
John
Please enter the phone number of your friend:
1234567890
Please enter the email of your friend:
john@example.com
Please enter the company name of your friend:
ABC Inc.
Your friend has been added to the address book.
Please enter the name of your friend (or 'quit' to exit):
Mary
Please enter the phone number of your friend:
0987654321
Please enter the email of your friend:
mary@example.com
Please enter the company name of your friend:
XYZ Corp.
Your friend has been added to the address book.
Please enter the name of your friend (or 'quit' to exit):
quit
Your address book contains the following friends:
Name: John, Phone Number: 1234567890, Email: john@example.com, Company Name: ABC Inc.
Name: Mary, Phone Number: 0987654321, Email: mary@example.com, Company Name: XYZ Corp.