2

我正在一个课堂实验室工作,并且让 bwcomw 坚持我们必须编写的一种方法:

Member[] getMembersByYear(int firstYear, int last year)– 查找并返回在两个指定年份之间加入的所有成员,包括在内。此方法返回 Java 一维数组中的成员。数组中不能有空槽。

我对如何解决这个问题有点困惑,我会很感激任何建议。这是我到目前为止所写的:

public class Club
{
// Define any necessary fields here ...
private ArrayList <Member> members;

/**
 * Constructor for objects of class Club
 */
public Club()
{
    // Initialise any fields here ...
    members = new ArrayList <Member>();
}

/**
 * Add a new member to the club's list of members.
 * @param member The member object to be added.
 */
public void join(Member member)
{
    members.add(member);
}

/**
 * @return The number of members (Member objects) in
 *         the club.
 */
public int numberOfMembers()
{
    if(members.size() > 0){
        return members.size(); 
    }
    else{
    return 0;
}
}

public void showMembers(){
    for(Member display: members){
        System.out.println(display.toString());

    }
}

public void showMembersByYear(int year){
    for(Member byYear: members){
         if(byYear.getYear() > 0){
             showMembers();
            }

    }
}

public Member[] getMembersByYear(int firstYear, int lastYear)
{
    Member checker = new Member();                                        //does not work, no constructor member() exists
    while((firstYear <= checker.getYear()) && (lastYear >= checker.getYear())){

    }


}

public void removeMembersByYear(int year){
    Iterator it = members.iterator();



}
}
4

2 回答 2

0

好的。很高兴看到你成功了!首先,在您的方法中,您可以创建一个ArrayList. 然后是循环遍历members数组的情况,当一年介于给定范围之间时,您应该将其添加到新的ArrayList. 然后,只需返回ArrayList.toArray方法。就像是:

 public Member[] getMembersInYear(int firstYear, int secondYear)
 {
     ArrayList<Member> membersInRange = new ArrayList<Member>();
     for(every member in members) {
         if(is in year) {
             membersInRange.add(currentMember);
         }
     }
     return membersInRange.toArray();
 }

这将返回一个没有空值的数组,其中仅包含年份介于firstYear和之间的成员secondYear

于 2013-04-21T10:49:07.217 回答
0

尝试这个

public Member[] getMembersByYear(int firstYear, int lastYear) {
    Iterator membersIterator = members.iterator(); 
    ArrayList<Member> returnValues = new ArrayList<Member>();
    while (membersIterator.hasNext()) {
        Member current = (Member)membersIterator.next();
        if ((current.getYear()>=firstYear) && (current.getYear()<=lastYear)) {
            returnValues.add(current);
        }
    }
    Member[] toReturn = new Member[returnValues.size()];
    returnValues.toArray(toReturn);
    return toReturn;
}

希望这可以帮助

于 2013-04-21T10:52:58.640 回答