import java.io.*; import java.text.DecimalFormat; public class Average { static BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in)); /***************************************************************** * 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) throws IOException { int sum = 0, value, count = 0; double average; DecimalFormat fmt = new DecimalFormat ("0.###"); // initialize the loop control variable System.out.print ("Enter an integer (0 to quit): "); value = Integer.parseInt(keyboard.readLine()); while (value == 0) { System.out.print ("At least give me one: "); value = Integer.parseInt(keyboard.readLine()); } 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 = Integer.parseInt(keyboard.readLine()); } 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); } }