import java.util.Scanner; /* Java application that reports the arithmetic mean (i.e., average) ** of the integer values supplied to it by the user. The program ** prompts the user to enter each value; -9999 signals end-of-input. * * Author: R. McCloskey (based on a program by Paul Jackowitz) * Date: August 24, 2010; updated August 2020; updated Sept. 2021 */ public class MeanProgram { // "Sentinel" value that, when entered by the user, signals that // there is no more input to be processed. private static final int EOF_SENTINEL = -9999; // A Scanner object can read data from an input source; // here that will be the user's keyboard. private static Scanner keyboard = new Scanner(System.in); // When a Java application is run, execution begins in the main() method. public static void main(String[] args) { int inputVal; // the most recent input entered by the user int sumSoFar; // the sum of inputs entered so far int count; // the # of inputs entered so far double mean; // the result sumSoFar = 0; count = 0; // obvious initializations // read first input value inputVal = getAnInput(); // accept and process input values until a zero value is entered while (inputVal != EOF_SENTINEL) { sumSoFar = sumSoFar + inputVal; // add latest input to running total count = count + 1; // increment counter inputVal = getAnInput(); // read next input via method call } // now report the result System.out.print("The mean of the integers entered is "); if (count > 0) { mean = (double)sumSoFar / (double)count; System.out.println(mean); } else { System.out.println("undefined"); } } /* Prompts the user to enter an input, accepts the response, ** and returns it to the caller. */ private static int getAnInput() { System.out.printf("Enter an integer (%d to quit): ", EOF_SENTINEL); return keyboard.nextInt(); } }