0
我正在做一個程序,得到的平均值,並且在陣列推算數字的標準偏差。然而,我只會遇到一件事:每當返回平均值和標準偏差時,它就會顯示爲不是數字。代碼有什麼問題?平均值和標準偏差方法返回的NaN的
這裏的方法:
public mainFrame() {
initComponents();
}
private double avg;
private double stdDeviation;
private double[] gradeArray;
/**
*
* @param gradeArray
* @param numElem
* @return
*/
public double getAverage (double[] gradeArray, int numElem) {
double sum = 0;
for(int i=0;i<numElem;i++){
sum = sum + gradeArray[i];
}
return (sum/numElem);
}
public double getStdDev (double[] gradeArray, int numElem, double avg){
double sum = 0;
for(int i = 0;i<numElem;i++){
sum = sum + Math.pow((gradeArray[i]-avg),2);
}
return Math.sqrt(sum/numElem);
這裏是事件代碼時「輸入級別」按鈕被點擊:
final int SIZE = 25;
double[] gradeArray = new double[SIZE];
String s;
int numElem = 0;
double average = 0;
for(int i=0;i<=SIZE;i++){
s = (String)JOptionPane.showInputDialog("Enter Grade","");
if (s == null || s == ("")){
break;
}
else{
try{
gradeArray[i] = Double.parseDouble (s);
average = getAverage(gradeArray,numElem);
stdDeviation = getStdDev(gradeArray,numElem,avg);
txtGradeEntered.setText(1 + i + "");
txtMean.setText(average +"");
txtStdDev.setText(stdDeviation+"");
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "Your input must be numeric!","Bad Data!",0);
}
catch (ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog (null, "You can only input 25 values!","Too much data!",0);
}
}
}
您是否嘗試過使用調試器? –
'numElem'從0開始。因此在'getAverage'中,你除以0。 –