Search code examples
javajcreator

The mean and the standard deviation of the values in its array parameter


Here's My Code; and I can find an array with this and I would like to calculate the mean of the values (overall) after this I would like to calculate standard deviation of this but I couldn't understand the question exactly so I dont have a method for now. Here's the question for standard deviation (Write a method that takes two parameters --a set of int values in an array and a double value representing their mean-- and computes and returns the standard deviation of the values using the given mean.)

import java.util.*;

public class Test
{ 
    final static int N = 100;
    static int limit = 0;
    static int[] list;
    static int i, j;
    static int sum = 0;
    static Scanner scan = new Scanner (System.in);

 public static int[] generateArray ()
 {

    System.out.print ("Enter your array limit: ");
    limit = scan.nextInt();

    list = new int[limit];

    for(i = 0; i < limit; i++)
    {
        list[i] = (int) (Math.random() * 2 * N - N);
    }
    return list;
 }

 public static void printArray() 
 {      
    for(j = 0; j < limit; j++)
        System.out.print (list[j] + "\t");
 }

 public static void meanArray()
 {
    sum = sum + list[j];           //PROBLEM HERE
    System.out.println (sum);
 }

 public static void main(String[] args) 
 {      
     generateArray();
     printArray();
     meanArray();                  //PROBLEM HERE
 }

}

Solution

  • To generate the mean value, add up all values in your list and devide them by the number of values:

    public static void meanArray() {
        double result = 0;
        for(int i : list) {
            result += i;
        }
        result /= list.length;
        System.out.println(result);
    }