ClubMembers
is #3 from the from the 2021 AP Computer Science A Free Response problems.
https://apcentral.collegeboard.org/pdf/ap21-frq-computer-science-a.pdf?course=ap-computer-science-a
Part (a) addMembers
method
public void addMembers(String[] names, int gradYear)
{
for(String name : names)
memberList.add(new MemberInfo(name, gradYear, true));
}
This could also be solved with a regular for
loop. On the free response, when in doubt, use a regular loop (for
or while
).
See Enhanced for loop exercises for information on when enhanced for loops are appropriate, and to practice with them.
Part (b) removeMembers
method
public ArrayList<MemberInfo> removeMembers(int year)
{
ArrayList<MemberInfo> goodStanding = new ArrayList<MemberInfo>();
int i = 0;
while(i < memberList.size())
{
if(memberList.get(i).getGradYear() <= year)
{
MemberInfo removed = memberList.remove(i);
if(removed.inGoodStanding())
goodStanding.add(removed);
}
else
i++;
}
return goodStanding;
}
See ArrayList practice for details on adding to and removing from an ArrayList
within a loop.
2021 AP CS Exam Free Response Solutions
- WordMatch Free Response Solution
- CombinedTable Free Response Solution
- ArrayResizer Free Response Solution
Additional ArrayList
resources
Help & comments
Get help from AP CS Tutor Brandon Horn