-2

I'm writing a program that displays the Maximum, Minimum, and average of an array

So far I have methods for the max and min but not for the average.

My code:

class Test
{
    public static void main(String[] args) 
    {
        int[] arr = {5,12,-3,7,3,22,31,2,16,56};
        System.out.println(minValue(arr));
    System.out.println(maxValue(arr)); 
    System.out.println(avgValue(arr)); 

    }// end of Main

  // Array Methods
    public static int minValue(int[] nums)
    {
         int minValue = nums[0]; 
    for(int i=1;i < nums.length; i++){ 
      if( nums[i] < minValue){ 
        minValue = nums[i]; 
      } 
    } 
    return minValue; 
  } 
    

  public static int maxValue(int[] nums)
    {
         int maxValue =nums[0]; 
    for(int i=1;i < nums.length ;i++){ 
      if( nums[i] > maxValue){ 
         maxValue = nums[i]; 
      } 
    } 
    return maxValue; 
    }

   public static int avgValue(int[] nums)
    {
    int temp = 4;

    return temp;
    }
  
}// end fo class

Right now the method to find the average is filled with a placeholder integer that always returns "4"

How would I write a message to find the average of my array?

3 Answers3

0

An easy way would be:

  public static double avgValue(int[] nums) {
    int total = 0;

    for(int i = 0; i < nums.length; i++) {
      total = total + arr[i];
    }

    double average = total / (double) nums.length;
    return average;
  }
0

This is the proper way:

public static float avgValue(int[] nums)
{
    float sum = 0.0f;
    float avg = 0.0f;
    for(int i=0; i < nums.length;i++){
        sum += nums[i];
    }
    avg = sum/nums.length;
    return avg;
}
Ashish Dahiya
  • 650
  • 5
  • 14
-1

Using Java Streams

int[] data = {1,5,4,9,2,1,4,7,8};

IntSummaryStatistics s = Arrays.stream(data).summaryStatistics();
System.out.println("Average: " + s.getAverage());
System.out.println("Count: " + s.getCount());
System.out.println("Min: " + s.getMin());
System.out.println("Max: " + s.getMax());
System.out.println("Sum: " + s.getSum());

Output

Average: 4.555555555555555
Count: 9
Min: 1
Max: 9
Sum: 41
Ajeetkumar
  • 1,271
  • 7
  • 16
  • 34