简体   繁体   中英

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. 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. 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. If I do something like the code below, it takes each test value and divides it by 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

    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:

[80,
 82,
 63,
 80]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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