Get the mean of an array in Java

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:
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments