2D数组列平均java

时间:2017-04-14 01:39:14

标签: java arrays for-loop

我有2个数组,<?php $ethnic_later = 'niet opgegeven'; $ethnic_array = array( 'Blank' => 'blanke', 'getint' => 'getinte', 'Aziatisch' => 'Aziatische', 'Zuid-Amerikaans' => 'Zuid Amerikaanse' ); if (isset($ethnic_array[$ethnic])) { $ethnic = $ethnic_array[$ethnic]; }else{ $ethnic = $ethnic_later; } echo 'een mooie ' . $ethnic . ' kleur'; String[][] names,用于存储我尝试在更长的代码中作为表格打印的类的名称和等级。我能够用我在main中调用的方法计算每行的平均值。我很难弄清楚如何做每列的平均值。任何建议,将不胜感激。对于行平均值,我写了一个方法:

int[][] grades

然后用

打印在我的主页上
//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

4 个答案:

答案 0 :(得分:0)

使用您感兴趣的列的值创建一个新数组; rowAverage将计算该数组的平均值(即该列)。重复每列。

答案 1 :(得分: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;
           }
    }
}

答案 2 :(得分: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;
 }

答案 3 :(得分: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);
    }