# Example: Console: Min, max, average

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 ``` ```// File : flow-loops/MaxMinAvgIncome.java // Purpose: Calculates income statistics. Illustrates: // * Running calculation of minimum and maximum. // * Initializing min and max values to largest/smallest // possible values. Alternative is to use first value. // * Reads until non-number / EOF. // Alternative is read until sentinel value. // * Average is total divided by number of values. // Name : Fred Swartz - 2006-Dec-14 - Placed in public domain. import java.util.*; public class MaxMinAvgIncomeS { public static void main(String[] args) { Scanner input = new Scanner(System.in); //... These variables hold the max and min incomes. double maxIncome = Double.MIN_VALUE; // Maximum income. //Note 1 double minIncome = Double.MAX_VALUE; // Minimum income. //... These variables are used to compute the average. int count = 0; // Number of input values. double totalIncome = 0; // Total of all incomes. //... Loop until negative number is entered. System.out.println("Enter incomes. Terminate with EOF or non-number."); while (input.hasNextDouble()) { //... Get the next value. double income = input.nextDouble(); //... Compare this value to max and min. Replace if needed. if (income > maxIncome) { maxIncome = income; } if (income < minIncome) { minIncome = income; } //... Keep track of these values for average calculation. count++; // Count the number of data points. totalIncome += income; // Keep a running total. } //... Be sure user entered at least one data point. if (count > 0) { //Note 2 //... Display statistics double average = totalIncome / count; System.out.println("Number of values = " + count); System.out.println("Maximum = " + maxIncome); System.out.println("Minimum = " + minIncome); System.out.println("Average = " + average); } else { System.out.println("Error: You entered no data!"); } } } ```

### Notes

1. One way to initialize the maximum and minimum is to set them to values so low/high that any legal input value will surely replace the initial values. This uses the smallest and largest possible int values for that purpose. An alternative way to initialize them is to set them to the first legal value that is read in, which could be done with an "if" statement that checks initializes them when count is zero.
2. Check to make sure some data has been entered to avoid division by zero and meaningless output.