我有2個陣列,String[][] names
和int[][] grades
,存儲我想在更長的代碼,以打印爲表一類的名稱和等級。我能夠用我在main中調用的方法計算每行的平均值。我很難弄清楚如何做每列的平均值。任何建議,將不勝感激。該行平均我寫了一個方法:二維數組列一般的Java
//determine average for each student
public double rowAverage(int[] rowOfGrades) {
int total = 0;
//sum grades for each student
for(int grade : rowOfGrades){
total += grade;
}
//return average of student grades
return (double) total/rowOfGrades.length;
}//end getAverage
,然後印在我的主與
//creates rows and columns of text for array names and grades
for(int student=0; student<names.length; student++) {
System.out.printf("%s",names[student]); //student name
for(int test : grades[student]) {
System.out.printf("\t%7d",test); //test grades
}
//call method getAverage to calculate students grade average
//pass row of grades as the argument to getAverage
double average = rowAverage(grades[student]);
System.out.printf("%12.2f", average);
}