/** * This is the cleaned up version of a program to calculate * the average and standard deviation of a list of numbers entered * from the keyboard * * Written by: Stuart Hansen * Date: October 23, 2002 */ import java.util.*; public class Stats { public static void main (String [] args) { int count = 0; // count the number of numbers double sum = 0.0; // Sum the numbers entered double sumSqr = 0.0; // the sum of the squares double number; // The current number Scanner input = new Scanner(System.in); // Prime the pump System.out.print("Enter a number, negative to terminate: "); number = input.nextDouble(); // Continue until the user enters a negative number while (number >= 0.0) { // Add and count sum += number; sumSqr += number*number; count++; // Enter the next number System.out.print("Enter a number, negative to terminate: "); number = input.nextDouble(); } // Make certain that at least one number was entered before dividing if (count > 0) { // Report the statistics double average = sum/count; System.out.println("The average is " + average); double standardDeviation = Math.sqrt(sumSqr/count-average*average); System.out.println("The standard deviation is " + standardDeviation); } else System.out.println("No numbers entered!"); } }