Computer Science Example
Calculating a person's body mass index.

import java.io.*;
import java.text.*;

class BodyMassIndex
{
     public static void main (String [] args)
     {
          Person person = new Person ();
          person.getData ();
          person.displayData ();
     } // method main
} // class BodyMassIndex

// Class that displays a person's body mass index.
class Person
{
     private String name;
     private double weight, height, heightFeet, heightInches;
 
     // Read the data for the body mass index from the keyboard.
     public void getData ()
     {
          BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
          try
          {
               System.out.print ("Name: ");
               name = stdin.readLine ();
               System.out.print ("Weight: ");
               weight = Double.parseDouble (stdin.readLine ());
               System.out.print ("Height in Feet: ");
               heightFeet = Double.parseDouble (stdin.readLine ());
               System.out.print ("Height in Inches: ");
               heightInches = Double.parseDouble (stdin.readLine ());
               height = 12 * heightFeet + heightInches;
          }catch (NumberFormatException e){System.out.println ("Number Format Exception");}
          catch (IOException e) {System.out.println ("IO Exception");}
     } // method getData
 
     // Calculate the body mass index and display it on the screen.
     public void displayData ()
     {
          double bmi = calculateBMI();
          System.out.println (name + "'s body mass index is " + decimals (bmi));
     } // method displayData
 
     // Calculate the body mass index using English units.
     private double calculateBMI ()
     {
          double bmi;
          bmi = (705 * weight) / (height * height);
          return bmi;
     } // calculateBMI
 
     // Format a double for string output with two decimal places.
     private String decimals (double number)
     {
          DecimalFormat decFor = new DecimalFormat ();
          decFor.setMaximumFractionDigits (2);
          decFor.setMinimumFractionDigits (2);
          return decFor.format (number);
     } // decimals
} //class Person