向ArrayList添加多个参数

时间:2016-04-11 21:21:46

标签: java arraylist enumerated-types

我无法搞清楚这项任务。我只是在寻找特定问题的答案,因为在向Array List添加内容时我似乎有点迷失。我有一个健身房'使用add方法的类,它应该创建一个'成员'来自会员类的对象。

public class Gym {

    private String gymName;              // Identifies the name of the gym.
    private ArrayList<Member> members;   // A list of member objects.
    private double[] gymRates;           // A map that relates membership type to its fee.
    private double trainerRate;          // indicates rate charge for one hour with PT.

    /**
     * Add a new member to a gym's list of members.
     * 
     * @param hoursQ1    number of personal trainer hours the member had for quarter one.
     * @param hoursQ2    number of personal trainer hours the member had for quarter two.
     * @param hoursQ3    number of personal trainer hours the member had for quarter three.
     * @param hoursQ4    number of personal trainer hours the member had for quarter four.
     */
    public void addMember(String firstName, String lastName, MembershipType memberType, int hoursQ1, int hoursQ2,
            int hoursQ3, int hoursQ4) {
        members.add(new Member(firstName, lastName, memberType, hoursQ1, hoursQ2, hoursQ3, hoursQ4));
    }

    /**
     * Add a specified member to a gym's list of members.
     * 
     * @param member     the member to add.
     */
    public void addMember(Member member) {
        Member.add(member);
    }
}

public class Member {
    private String firstName;
    private String lastName;
    private MembershipType memberType;
    private int[] trainerHours = new int[4];
}

根据我的理解,错误(参数长度不同),是因为参数的小时数为Q1-Q4,而且我没有正确地将它们初始化为trainerHours数组?

另外,我的trainerHours数组应该使用枚举类型类&#39; Quarter&#39;作为指数,Q1,Q2,Q3,Q4。我还没想到这个...... 对不起格式化,这里也有问题! ;)

2 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题:

  • 首先,当您调用新成员(...)时,未定义该函数,因为您尚未为类成员
  • 定义具有这些参数的构造函数
  • 第二,你的第二个addMember方法错了,它应该是members.add(...)而不是Member.add

答案 1 :(得分:0)

我应该为Member类创建以下构造函数:

public Member(String pFirstName, String pLastName, MembershipType pMemberType, int hoursQ1, int hoursQ2, int hoursQ3, int hoursQ4){
    firstName = pFirstName;
    lastNam = pLastName;
    memberType = pMemberType;
    trainerHours[0] = hoursQ1;
    trainerHours[1] = hoursQ2;
    trainerHours[2] = hoursQ3;
    trainerHours[3] = hoursQ4;
}