2017-04-14 49 views
1

我有2個陣列,String[][] namesint[][] 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); 
    } 

回答

0

對於你必須遍歷每個學生測試:

for (int test = 0; test < grades.length; test++) { 
    int total = 0; 
    for(int student=0; student<names.length; student++) { 
    total += grades[student][test] 
    } 
    double avgForTest = (double) total/names.length; 
} 
0

創建一個新的陣列瓦特/你感興趣的列中的值; rowAverage將計算該數組的平均值(即該列)。重複每一列。

0

訪問行,你將不得不例如訪問其長度字段的每列names[student].length

例如

int[][] towers = new int[8][8]; 
int myNumber=25; 
for(int row=0;row<towers.length;++row) 
{ 
    for(int column=0;column<towers[row].length;++column) 
    {  
      if(myNumber==towers[row][column]) 
      { 
       System.out.println("I found you"); 
       column=towers[row].length; 
       row=towers.length; 
      } 
    } 
} 
0

你可以嘗試像

for (int i = 0; i < 2; i++) { 
     int rowSum = 0; 
     int colSum = 0; 
     double rowAvg = 0.0; 
     double colAvg = 0.0; 
     for (int j = 0; j < 2; j++) { 
      rowSum += arr[i][j]; 
      colSum += arr[j][i]; 
     } 
     rowAvg = rowSum/2.0; 
     colAvg = colSum/2.0; 
     System.out.println(i + " row average: " + rowAvg); 
     System.out.println(i + " column average: " + colAvg); 
    }