这是用于计算平均值的代码,运行项目时出现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());
         }
        }

最佳答案

我认为问题可能在于这行代码:

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;

关于java - 如何解决NaN错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29196222/

10-10 23:47