Java / BlueJ - 无法打印出ArrayList中的项目

时间:2014-09-08 11:58:45

标签: java arraylist accessor bluej mutators

我遇到了在ArrayList中循环/返回正确项目的问题。当我运行我的程序,并使用我的访问器方法时,它返回终端中的项目,如“Member @ 13243”,而不是我试图返回的实际成员。我有两个班,一个是“家庭”,一个是“会员”。

我的任务是: 2)getMembers() - 返回已添加到Family的成员列表。 3)getMembers(string s) - 返回已添加到Family的成员列表。 一个。如果指定的性别无效,则应输出错误。 4)showMembers() - 使用Member的toString打印已添加到Family的成员列表 5)showMembers(字符串s) - 使用Member的toString打印已添加到一个系列的成员列表 指定的性别。

我的家庭代码:

  public class Family

 {
    // instance variables - replace the example below with your own
   public int ID;
   public String FamilyName;
   public String Address;
   public String City;
   public String State;
   public String ZipCode;
   public ArrayList<Member> list;

   public Family(int ID, String FamilyName, String Address, String City, String State, String        ZipCode)
   {
    this.ID = ID;
    this.FamilyName = FamilyName;
    this.Address = Address;
    this.City = City;
    this.State = State;
    this.ZipCode = ZipCode;
    list = new ArrayList<Member>();
   }

public void addMember(Member m )  {

   list.add(m);

}


private ArrayList<Member> getMembers(){
return list;
}


public void showAll(){
System.out.println(ID);  
System.out.println(Member.memberName);
System.out.println(FamilyName);
System.out.println(Member.memberSex); 
System.out.println(Address); 
System.out.println(City); 
System.out.println(State); 
System.out.println(ZipCode); 

}

我的班级成员代码:

 public class Member 
 {

   private String memberName;
   private String memberSex;



   public Member(String memberName, String memberSex){

    this.memberName = memberName;
    this.memberSex = memberSex;


     if (memberSex == "M"){
    memberSex = "M";}

    else if (memberSex == "F"){
    memberSex = "F";}

    else System.out.println("Please enter M or F for sex");


    }

    public String getMemberName(){
        return memberName;
    }

    public String getMemberSex(){
       return memberSex;
    }

1 个答案:

答案 0 :(得分:0)

您应该在Member类中覆盖toString方法。

 @Override
    public String toString() {
    return "Member: "+memberName, "Sex "+memberSex;

}