如何提取'for'循环方法?

How to extract 'for' loop Method?

我正在尝试提取我的 'for' 循环以便在 printPartyBreakdownInHouse() 方法中调用它。基本上消除了重复代码或 "code smell" 以及我的 printdetails() 方法的任何可能性,但是这样做时我得到的结果是“2”。有什么想法吗?

public void printPartyBreakdownInSenate() {
    int numDemocrats = 0;
    int numRepblican = 0;
    int numIndepent = 0;

    String senateData;
    ArrayList<MemberOfCongress> members;


    senateData = CongressDataFetcher.fetchSenateData(congressNum);
    members = parseMembersOfCongress(senateData);

    for (MemberOfCongress party : members){
            if (party.getParty().equals("D")){
                numDemocrats++;
            }
            else if (party.getParty().equals("R")){
                numRepblican++;
            }
            else if (party.getParty().equals("I")){
                numIndepent++;
           }
   }
   pintDetails(numIndepent, numIndepent, numIndepent, numIndepent, members);
}

/**
 * printDetails method
 */
void pintDetails(int congressNum, int numDemocrats, int numRepblican, int numIndepent, ArrayList<MemberOfCongress> members){
    System.out.println("Number of Members of the Senate of the " +  congressNum + " Congress : " + members.size() );
    System.out.println("# of Democrats: " + numDemocrats);
    System.out.println("# of Republican: " + numRepblican);
    System.out.println("# of Indep: " + numIndepent);
}

/**
 * Calculate and print the number of Democrats, Republicans, and Independents in this House
 */
public void printPartyBreakdownInHouse(){
    String houseData;
    ArrayList<MemberOfCongress> members;
    houseData = CongressDataFetcher.fetchHouseData(congressNum);
    members = parseMembersOfCongress(houseData);
}

你的错误在这里:

pintDetails(numIndepent, numIndepent, numIndepent, numIndepent, members);

您正在打印 numIndepent 4 次...?

pintDetails(numIndepent, numIndepent, numIndepent, numIndepent, members);

应该阅读

pintDetails( [VARIABLE NOT IN CODE], numDemocrats, numRepblican, numIndepent, members);

您可以使用一种方法,该方法接受 members 列表作为参数,returns 成员通过额外的助手 class 计数,如下所示:

class MemberCounter {
  int numDemocrats;
  int numRepblican;
  int numIndepent;
};

MemberCounter countMembers(List<MemberOfCongress> members) {
  MemberCounter counter = new MemberCounter();

  for (MemberOfCongress party : members) {
    if (party.getParty().equals("D")) {
      counter.numDemocrats++;
    }
    else if (party.getParty().equals("R")){
      counter.numRepblican++;
    }
    else if (party.getParty().equals("I")){
      counter.numIndepent++;
    }
  }

  return counter;
}