Java Notes

Maximum, Minimum, Average Height

This program prompts for name/height pairs and displays the maximum, ,minimum, and average heights.

  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 
// File   : flow-loops/MaxMinAvgHeight.java
// Purpose: Calculates maximum, minimum, and average height.
// Name   : Fred Swartz
// Date   : 2006-04-24

import javax.swing.*;

public class MaxMinAvgHeight {

    public static void main(String[] args) {

        int maxHeight     = -999;  // Maximum height
        String tallestPerson = "nobody";
        int minHeight     =  999;  // Minimum height.
        String shortestPerson = "nobody";
        int totalHeights = 0;      // Total of all heights.
        int numberOfEntries = 0;   // Number of inputs.

        while (true) {
            //... Read in name, height
            String input = JOptionPane.showInputDialog(null, "Enter name and height");
            if (input == null || input.length() == 0) {
                break;
            }
            int spacePos = input.indexOf(" ");
            String name = input.substring(0, spacePos);
            String heightStr = input.substring(spacePos+1);
            int height = Integer.parseInt(heightStr);

            //... Check to see if this person is taller.
            if (height > maxHeight) {
                maxHeight = height;
                tallestPerson = name;
            }

            //... Check to see if this person is shorter.
            if (height < minHeight) {
                minHeight = height;
                shortestPerson = name;
            }

            //... Add to total and count.
            totalHeights += height;
            numberOfEntries++;
        }

        //... Display statistics
        double average = ((double)totalHeights) / numberOfEntries;
        JOptionPane.showMessageDialog(null,
                    "Maximum height = " + maxHeight + " " + tallestPerson
                  + "\nMinimum height = " + minHeight + " " + shortestPerson
                  + "\nAverage height = " + average);
    }
}