我编写了一个程序,允许我输入业务或个人联系人,然后才能查看它们。我已经为不同类型的联系人使用了子类。当我查看联系人时,我希望能够看到它们是商业用途还是个人用途,但是我们无法找到正确的方法。我已经包含了一段代码,显示了我如何输入它们以及我要求它们查看它们。
public static void addContact(ArrayList<Contact> ContactRecords) {
Scanner textIn = new Scanner(System.in);
Scanner keyIn = new Scanner(System.in);
System.out.println("First Name: ");
String firstName = textIn.nextLine();
System.out.println("Last Name: ");
String lastName = textIn.nextLine();
System.out.println("Address: ");
String address = textIn.nextLine();
System.out.println("Email Address: ");
String email = textIn.nextLine();
System.out.println("Phone: ");
String phone = textIn.nextLine();
System.out.println("Is this a 1) Personal or 2) Business?");
int choice = keyIn.nextInt();
if (choice == 1) {
System.out.println("Date of Birth: ");
String dateOfBirth = textIn.nextLine();
Personal aPersonal = new Personal(firstName, lastName, address,
email, phone, dateOfBirth);
ContactRecords.add(aPersonal);
}
if (choice == 2) {
System.out.println("Job Title: ");
String jobTitle = textIn.nextLine();
System.out.println("Organization: ");
String organization = textIn.nextLine();
Business aBusiness = new Business(firstName, lastName, address,
email, phone, jobTitle, organization);
ContactRecords.add(aBusiness);
}
}
public static void getRecords(ArrayList<Contact> ContactRecords)
{
Scanner keyIn = new Scanner(System.in);
System.out.println("Contacts who have been entered:");
for (int i = 0; i < ContactRecords.size(); i++) {
System.out.println(i + ") "+ ContactRecords.get(i).getFirstName() +
" " + ContactRecords.get(i).getLastName());
}
System.out.println("Please enter the number corresponding to the contact
you would like to view: ");
int choice = keyIn.nextInt();
System.out.println(ContactRecords.get(choice).toString());
}
}
所以现在当我查看我已添加的联系人时,我看到的是名字,姓氏,地址,电子邮件,电话,然后根据联系方式,出生日期(个人)或职位名称和组织(商业)。我还希望看到Business或Personal,当它返回我的联系信息但不确定时。我尝试添加到我的system.out.println ContactRecords.get(choice).get(Class)但是将其作为类contactlist.personal返回。我只想退回个人
答案 0 :(得分:0)
你可以做到
getClass().getSimpleName()
在联系人条目上。但我建议添加一个方法来联系getType()以返回类
上的静态字符串public class Business extends Contact {
private static final String TYPE = "Business";
...
@Override // method on Contact
public String getType() {
return TYPE
}
或返回枚举
public enum ContactType {
Personal, Bussiness
}
public class Business extends Contact {
private static final ContactType TYPE = ContactType.Business;
...
@Override // method on Contact
public ContactType getType() {
return TYPE
}