我试图提取我的'for'循环,以便在printPartyBreakdownInHouse()
方法中调用它。基本上删除任何重复代码或“代码味道”的机会以及我的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);
}
答案 0 :(得分:1)
您的错误在这里:
pintDetails(numIndepent, numIndepent, numIndepent, numIndepent, members);
您正在打印numIndepent 4次......?
答案 1 :(得分:1)
该行
pintDetails(numIndepent, numIndepent, numIndepent, numIndepent, members);
应该阅读
pintDetails( [VARIABLE NOT IN CODE], numDemocrats, numRepblican, numIndepent, members);
答案 2 :(得分:0)
您可以使用接受0, 0
列表作为参数的方法,并通过其他帮助程序类返回成员计数,如下所示:
A, B