import java.io.*; import java.text.DecimalFormat; import java.util.Scanner; public class Average { /***************************************************************** * Computes the average of a set of values entered by the user. * The running sum is printed as the numbers are entered. *****************************************************************/ public static void main (String[] args) { int sum = 0, value, count = 0; double average; DecimalFormat fmt = new DecimalFormat ("0.###"); Scanner scan = new Scanner(System.in); // initialize the loop control variable System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); while (value == 0) { System.out.print ("At least give me one: "); value = scan.nextInt(); } while (value != 0) { // sentinel value of 0 to terminate loop // increment the count and update the sum count++; sum += value; System.out.println ("The sum so far is " + sum); // update the loop control variable System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); } System.out.println ("\nNumber of values entered: " + count); // calculate the average and output to user average = (double) sum / count; System.out.println ("The average is " + fmt.format(average)); System.out.println ("The number itself is " + average); } }