Get the mean of an array in Java

0 min read 160 words

The challenge

It’s the academic year’s end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script.

Return the average of the given array rounded down to its nearest integer.

The array will never be empty.

Test cases

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;


public class SolutionTest {
  	@Test
	public void simpleTest() {
		assertEquals(2,School.getAverage(new int[] {2,2,2,2}));
		assertEquals(3,School.getAverage(new int[] {1,2,3,4,5}));
		assertEquals(1,School.getAverage(new int[] {1,1,1,1,1,1,1,2}));
	}
  

  
}

The solution in Java

Option 1:

public class School{

  public static int getAverage(int[] marks){
    int total = 0;
    
    for (int i=0; i<marks.length; i++) {
      total += marks[i];
    }
    
    return total/marks.length;
  }

}

Option 2 (using streams):

import java.util.*;
public class School{

  public static int getAverage(int[] marks){
    return (int) Arrays.stream(marks).average().orElse(Double.NaN);
  }

}

Option 3 (using streams (alternative)):

import java.util.stream.*;

public class School{

  public static int getAverage(int[] marks){
    return (IntStream.of(marks).sum())/marks.length;
  }

}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags