这是用于计算平均值的代码,当我运行项目时,我收到NaN错误
public static double calculateAverage(){
double attendence = 0;
int no_of_matches = 0;
double average =0;
for (Team t: ApplicationModel.getTeamList()){
for(Match m : ApplicationModel.getMatchList()){
if(m.getTeamname().equals(t.getName())){
attendence =+ (m.getAttendence());
no_of_matches ++;
}
}
average = attendence / no_of_matches ;
}
return average;
}
这是调用计算平均方法的代码
String[] columnNames = {"Name","Coaches","League","Division","Fulltime","Number of Coaches","Average Attendence"};
if (ApplicationModel.getTeamList()!=null){
int arrayIndex=0;
for (Team c :ApplicationModel.getTeamList()){
String[] currentRow = new String[7];
currentRow[0] = c.getNameAsString();
currentRow[1] = c.getCoachesAsString();
currentRow[2] = c.getLeague();
currentRow[3] = c.getDivision();
currentRow[4] = c.getFulltime();
currentRow[5] = Integer.toString(c.getCoaches().length);
currentRow[6] = Double.toString(c.calculateAverage());
rowInfo[arrayIndex]=currentRow;
arrayIndex++;
teamDisplay.append(c.toString());
}
}
答案 0 :(得分:3)
我认为问题可能就是这行代码:
attendence =+ (m.getAttendence());
不是将值添加到总变量,而是将总变量赋值给该值。另一个问题是你没有处理no_of_matches
(在命名约定方面是一个可怕的变量名)是0
的情况,即没有匹配。最后,average = attendence / no_of_matches
始终重新分配average
,从而放弃之前团队的任何结果。
代码建议:
double attendence = 0;
int matches = 0;
for (Team t: ApplicationModel.getTeamList())
{
for(Match m : ApplicationModel.getMatchList())
{
if(m.getTeamname().equals(t.getName()))
{
attendence += (m.getAttendence());
matches++;
}
}
}
return matches > 0 ? attendence / matches : 0D;
答案 1 :(得分:0)
我认为您可以在分区操作中使用之前修复NAN错误检查no_of_matches > 0
。
public static double calculateAverage(){
double attendence = 0;
int no_of_matches = 0;
double average = 0;
for (Team t: ApplicationModel.getTeamList()) {
for (Match m: ApplicationModel.getMatchList()) {
if (m.getTeamname().equals(t.getName())) {
attendence =+ (m.getAttendence());
no_of_matches ++;
}
}
if (no_of_matches > 0)
average = attendence / no_of_matches ;
}
return average;
}
附加说明,当您添加此项检查且no_of_matches
为0
时,您的平均值为0,表示您没有匹配。
希望这有帮助。