如何在一维数组中返回?

时间:2013-04-21 10:42:22

标签: java arrays

我正在上一个班级实验室,并且让bwcomw坚持我们必须编写的一种方法:

  

Member[] getMembersByYear(int firstYear, int last year) - 找到   并返回在两个指定年份(包括两年)之间加入的所有成员。这个   method返回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();



}
}

2 个答案:

答案 0 :(得分: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();
 }

这将返回一个没有空值的数组,该数组仅包含年份介于firstYearsecondYear之间的成员。

答案 1 :(得分: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;
}

希望这有帮助