我创建的方法可以找到2D数组中一行的平均值。该方法接受描述作为行的等级类别的字符。从那以后,我需要找到该行中所有项目的平均值。如何找到行并计算平均值?
这是我到目前为止所拥有的:
import java.util.Arrays;
public class GradeBook {
private String name;
private char[] categoryCodes;
private String[] categories;
private double[] categoryWeights;
private double[][] gradeTable;
public GradeBook(String nameIn, char[] categoryCodesIn,
String[] categoriesIn, double[] categoryWeightsIn) {
name = nameIn;
categoryCodes = categoryCodesIn;
categories = categoriesIn;
categoryWeights = categoryWeightsIn;
gradeTable = new double[5][0];
}
public double categoryAvg (char gradeCategory) {
double sum = 0.0;
double count = 0.0;
int index = 0;
if (gradeCategory == 'a')
index = 0;
else if (gradeCategory == 'q')
index = 1;
else if (gradeCategory == 'p')
index = 2;
else if (gradeCategory == 'e')
index = 3;
else if (gradeCategory == 'f')
index = 4;
return sum / count;
}
}
答案 0 :(得分:1)
选择行后,您只需在该行上进行简单的1D阵列平均。 类似的东西:
for(int i=0; i < array[index].length; i++){
sum = sum + array[index][i];
count++;
}
答案 1 :(得分:1)
你应该添加这样的东西到最后,所以你不要试图除以零:
if (count == 0) {
return 0;
} else {
return sum / count;
}