如何获得平均考试成绩的平均值,这些成绩按文件列组织?

问题描述

文件包含以下格式的数据:

Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10   
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88

我正在尝试找出如何获取每一列的总和(例如,测试1 = 82 + 92 + 68 + ...),从而最终计算出每个测试的平均分数。

这是我解析文件并进行其他计算的方式:

public class TestAverages
{
  private static int[] grades;
  private static int[] testTotal;
  private static int N;
  private static double classtotal;
  
  public static void main(String[] args) throws FileNotFoundException
  {
    File input = new File("TestData.txt");
    Scanner in = new Scanner(input);
    parseFile(in);
    
  }
  public static void parseFile(Scanner in) throws FileNotFoundException
  {
    TestAverages t = new TestAverages();
    in.nextLine(); //skips the first line of text in file (labels)
    double classAvg =0.0;
    
    while(in.hasNextLine())
    {
      String line = in.nextLine();
      String[] data = line.split("\\|");
      String name = data[0];
      
      grades = new int[data.length - 1];
      N = grades.length;
      for(int i = 0; i < N; i++)
      {
        grades[i] = Integer.parseInt(data[i + 1]);

      }
      
      System.out.println(name);
      System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
      classAvg = t.getClassAvg(grades);
     
      System.out.println("Test Average: " + t.getTestAvg(grades) + "%\n");
    }
    System.out.printf("\nClass Average: %.2f%%\n",classAvg );
  }
  
  
  public double getStudentAvg(int[] grades)
  {
    double total = 0.0;
    double avg = 0.0;
    int N = grades.length;
    
    for(int i = 0; i < N; i++){
      total += grades[i];}
    
    avg = total / N;
    
    return avg;
  }
  
  
  public double getClassAvg(int[] grades)
  {
    double classtotal = getStudentAvg(grades) / N;
    double classAvg =0.0;
    
    classtotal += classtotal;
    classAvg = classtotal;
    
    return classtotal;
  }
}

如果格式不符合标准,请原谅。

目前,我的主要问题是如何为每位学生提取每项考试的分数并进行汇总。

解决方法

如果您已经知道文件中总共有10个测试,那应该很容易。

您可以将int[] testTotal = new int[10];的{​​{1}},testTotal[0] = sum-of-first-column等等。 。

您可以阅读其中的每一行,并以testTotal[1] = sum-of-second-column作为正则表达式来分隔它们

在循环中时,请"\\|"testTotal[0] += data[1]。 。 。 testTotal[1] += data[2]因为testTotal[9] += data[10]是学生的名字。

,

正在计算每个学生的考试成绩。您需要的是班级平均水平和考试平均水平。

  • 考试平均值是每次考试的平均分数。
  • 学生平均数是每个学生的平均考试成绩
  • 班级平均水平是整个班级在所有测试中的表现。

考虑三个测试

            test1   test2  test3   student average
student1      90      80     70          240/3
student2     100      90     90          280/3
student3      80      80     90          250/3

testAvg      270/3    250/3  250/3

class avg = (270 + 250 + 250)/9   or     (240+280+250)/9      

因此,您需要以这种方式读入值,以便于进行其他计算。对于数据,我建议使用Map<String,List<Integer>>,其中字符串是学生姓名,列表是每个学生的考试成绩。或者,您可以使用2D int数组。但是您需要保存分数,以便可以对测试分数进行列平均。大部分工作已经完成。

另外,我注意到了两个问题。您调用方法getTestAvg但未声明它,而您声明方法getClassAvg但从未调用它。