用java编写:【问题描述】编程实现如图所示的类间关联关系(双向关联) Contact -contactId:int Phone -name:String -phoneNum:String -isFreqContact:boolean 1 1 ..* -phoneArray:ArrayList<Phone> -type:String -aContact:Contact getPhones():arrayList addPhoneToContact(aPhone:Phone):void 【输入形式】 输入分4行, 第1行:联系人ID联系人姓名 第2行:第一个联系电话号码联系电话类型 第3行:第二个联系电话号码联系电话类型 第4行:第三个联系电话号码联系电话类型
时间: 2024-02-07 20:02:08 浏览: 70
以下是Java代码实现:
```java
import java.util.ArrayList;
class Contact {
private int contactId;
private String name;
private ArrayList<Phone> phoneArray = new ArrayList<Phone>();
public Contact(int contactId, String name) {
this.contactId = contactId;
this.name = name;
}
public ArrayList<Phone> getPhones() {
return phoneArray;
}
public void addPhoneToContact(Phone aPhone) {
phoneArray.add(aPhone);
aPhone.setContact(this);
}
// getter and setter methods
}
class Phone {
private String name;
private String phoneNum;
private boolean isFreqContact;
private String type;
private Contact aContact;
public Phone(String name, String phoneNum, String type) {
this.name = name;
this.phoneNum = phoneNum;
this.type = type;
}
public void setContact(Contact aContact) {
this.aContact = aContact;
}
// getter and setter methods
}
public class Main {
public static void main(String[] args) {
// 读入联系人信息
String[] contactInfo = new String[2];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
contactInfo[i] = sc.nextLine();
}
Contact aContact = new Contact(Integer.parseInt(contactInfo[0]), contactInfo[1]);
// 读入电话信息
for (int i = 0; i < 3; i++) {
String[] phoneInfo = sc.nextLine().split(" ");
Phone aPhone = new Phone(phoneInfo[0], phoneInfo[1], phoneInfo[2]);
aContact.addPhoneToContact(aPhone);
}
// 输出联系人的电话信息
ArrayList<Phone> phones = aContact.getPhones();
for (Phone phone : phones) {
System.out.println(phone.getName() + " " + phone.getPhoneNum() + " " + phone.getType());
}
}
}
```
输入样例:
```
123 John
12345678901 mobile
98765432109 home
13579246810 work
```
输出样例:
```
12345678901 mobile
98765432109 home
13579246810 work
```
阅读全文