有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java查找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;
  }
}

共 (2) 个答案

  1. # 1 楼答案

    一旦选中该行,您所要做的就是在该行上进行简单的1D数组平均。 比如:

    for(int i=0; i < array[index].length; i++){
          sum = sum + array[index][i];
          count++;
    }
    
  2. # 2 楼答案

    您应该在末尾添加类似的内容,这样您就不会试图除以零:

    if (count == 0) {
        return 0;
    } else {
        return sum / count;
    }