Software & Finance





Java - Calculate Mean





Here is the Java Source to calculate mean for a given set of numbers.

 

Source Code


import java.io.*;

 

 

class CalcMean {

 

    public static void main(String[] args) {

 

            String inpstring = "";

            InputStreamReader input = new InputStreamReader(System.in);

            BufferedReader reader = new BufferedReader(input);

 

            try

            {

                  System.out.print("Enter a Number Elements to calculate Mean:");

                  inpstring = reader.readLine();

 

                  long max = Long.parseLong(inpstring);

                  long[] arrElements = new long[100];

                  for (int i = 0; i < max; i++)

                  {

                        System.out.print("Enter [" + (i + 1) + "] Element: ");

                        inpstring = reader.readLine();

                        arrElements[i] = Long.parseLong(inpstring);

                  }

 

                  double total = 0;

                  for(int i = 0; i < max; i++)

                  {

                        total += arrElements[i];

                  }

 

                  double mean = total / max;

 

                  System.out.println("Mean: " + mean);

            }

            catch (Exception e)

            {

                  e.printStackTrace();

            }

    }

}

 

 

Output


D:\Program Files\Java\jdk1.6.0_23\bin>java CalcMean

Enter a Number Elements to calculate Mean:5

Enter [1] Element: 10

Enter [2] Element: 20

Enter [3] Element: 20

Enter [4] Element: 10

Enter [5] Element: 30

Mean: 18.0