ross.c ross.c - 3 months ago 34
Java Question

computing mean and standard deviation

creating a program that enables the user to enter an integer N, then reads N double values, and prints their mean (average value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by N - 1).
So far I have this code

import java.util.Scanner;

public class AVGDevi

{

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);



double x;

double sum = 0;

double average = 0;

double dev = 0;

double var = 0;

double sqrx = 0;

int n = 0;

do
{
System.out.println("Enter an integer:");
x = input.nextInt();
if (x == -1)
{
break;
}

sum += x;
n++;
average = sum / n;
sqrx += Math.pow(x-average,2);
var = sqrx / (n-1);
dev = Math.sqrt(var);


} while (x<= 0);

System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
}

}


test case:

5
1
2
3
4
5


Currently getting this output

Enter an integer:
Average: 5.0
Deviation: NaN


Output should be

Enter an integer: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Average value is: 3.0
The standard deviation is: 1.58


I'm not 100% sure what I'm doing wrong any help would be great :D !

Answer

You can use only while loop instead of do-while loop, as following:

public static void main(String[] args) 
{
Scanner input = new Scanner(System.in);




double y=-1;

double sum = 0;

double average = 0;

double dev = 0;

double var = 0;

double sqrx = 0;

int n = 0;


    System.out.println("Enter an integer:");
    y = input.nextInt();
    double z=y;
    int i=0;
    double x[] = new double[(int)z];
    while(y-->0){

   x[i] = input.nextDouble();

    sum += x[i];
   i++;         
    n++;
    average = sum / n;      


    }
    i=0;
    while(z-->0){
        sqrx += Math.pow(x[i]-average,2);
        i++;
    }
 var = sqrx / (n-1);
    dev = Math.sqrt(var);

System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
  }
Comments