我已经写了一个程序,允许我进入商业或个人联系,然后能够看到他们。我为不同类型的联系人使用了子类。当我查看联系人时,我希望能够看到他们是商务的还是个人的,但还没有找到正确的方法。我已经包含了一段代码,显示了我是如何输入它们的,以及我调用什么来查看它们。
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());
}
}所以现在,当我看到一个联系人,我看到的是我看到的名字,姓,地址,电子邮件,电话,然后取决于类型的联系,无论是出生日期(个人)或职位和组织(商业)。我也想看到,无论是商业或个人在我的时候,它返回我的联系方式,但只是不确定。我尝试将它添加到我的system.out.println ContactRecords.get(选择).get( class )中,但这会将它作为类contactlist.personal返回。我只想回私人的
发布于 2015-02-21 22:12:58
你可以
getClass().getSimpleName()在联系入口上。但是,我建议添加一个方法来联系getType(),以返回类上的静态字符串
public class Business extends Contact {
private static final String TYPE = "Business";
...
@Override // method on Contact
public String getType() {
return TYPE
}或者返回一个Enum
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
}https://stackoverflow.com/questions/28651880
复制相似问题