Java 如何解决NaN错误
这是计算平均值的代码,当我运行我的项目时,我得到了一个错误Java 如何解决NaN错误,java,nan,Java,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.getMatch
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());
不是将值添加到total变量,而是将total变量指定给该值。另一个问题是,您没有处理no\u of_matches
(就命名约定而言,这是一个糟糕的变量名)为0
的情况,即没有匹配项。最后,average=attentience/no\u of\u matches
始终重新分配平均值,从而放弃前一团队的任何结果
守则建议:
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;
我认为在除法操作中使用之前,如果no\u of\u matches>0
,您可以修复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 ++;
}
}
if (no_of_matches > 0)
average = attendence / no_of_matches ;
}
return average;
}
另一个注意事项是,当您添加此检查且无匹配项为0
时,您的平均值将为0,这意味着您没有匹配项
希望这能有所帮助。也许你在这里除以0average=attentence/no\u of\u matches代码>?如果你得到NaN,这意味着你将浮点零除以零。它是0.0,现在我知道问题了。我希望三支球队的成绩都能达到平均水平,但这只适用于一支球队,这可能就是为什么我非常希望你能提供帮助的原因。它的工作,但计算平均只有一个,这就是为什么打印0.0