简体   繁体   English

我将如何计算二维数组中的平均值?

[英]How would I calculate the average in a 2D Array?

To start, I'm not completely new to Java and I have taken a course on it.首先,我对 Java 并不完全陌生,并且我已经参加过这方面的课程。 Recently, I picked it up a again after a year and I'm a bit confused as to how to calculate an average in a 2D array of integers.最近,一年后我再次拿起它,我对如何计算二维整数数组的平均值有点困惑。 For example, here's an excerpt of code not including the average calculation:例如,这是一段不包括平均计算的代码摘录:

  //Program fills array with x students and their corresponding test grades for n amount of tests

  System.out.println("Amount of students?");
  int numstudents = sc.nextInt();
  System.out.println("Amount of tests?");
  int numtests = sc.nextInt();
  
  int[][] marks  = new int [numstudents][numtests];
  int[] average  = new int [numstudents];
  
  for (int i = 0; i < numstudents; i++) {
     for (int j = 0; j < numtests; j++) {
        System.out.println("Enter the mark for student " + (i+1) + " on test " + (j+1));
        marks[i][j] = sc.nextInt();
        //Array is filled with grades. 
     }
  }

Now let's say I wanted to calculate the average for each student and store the values in the average[] array.现在假设我想计算每个学生的平均值并将值存储在average[]数组中。 My main problem is figuring out how to loop it so that it includes every test for marks[0][j] and then moves on to marks[1][j] and so on.我的主要问题是弄清楚如何循环它,以便它包含对marks[0][j]的每个测试,然后转到marks[1][j]等等。 If I do something like the code below, it takes each test value and divides it by numtests .如果我执行以下代码之类的操作,它将获取每个测试值并将其除以numtests

 for (int i = 0; i < numstudents; i++) {
     for (int j = 0; j < numtests; j++) {
        average[i] = marks[i][j]/numtests;
        System.out.println("The average is " + average[i]);
     }
  }

I think average[i] should be calculated我认为应该计算平均[i]

    for (int i = 0; i < numstudents; i++) {
        //here
        for (int j = 0; j < numtests; j++) {
        }

How about writing codes like as follows?编写如下代码怎么样?

    int eachsum = 0;
    for (int i = 0; i < numstudents; i++) {
        for (int j = 0; j < numtests; j++) {
             eachsum += marks[i][j];
        }
        average[i] = eachsum/numtests;
        System.out.println("The average for student " + (i+1) + " is " + average[i]);
        eachsum = 0;
    }

You can do the following:您可以执行以下操作:

int[] average = Arrays.stream(marks)
        .map(ints -> Arrays.stream(ints).summaryStatistics().getAverage())
        .mapToLong(Math::round)
        .mapToInt(Math::toIntExact)
        .toArray();

Input:输入:

    int[][] marks = {
            {80, 70 ,90},
            {90, 65 ,90},
            {50, 70 ,70},
            {80, 75 ,85}
    };

Output: Output:

[80,
 82,
 63,
 80]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM