Source of BMIExceptHandling.java


  1: //BMIExceptHandling.java

  3: import java.util.Scanner;

  5: public class BMIExceptHandling
  6: {
  7:     public static void main(String[] args)
  8:     {
  9:         Scanner scnr = new Scanner(System.in);
 10:         int weightVal; // User defined weight (lbs)
 11:         int heightVal; // User defined height (in)
 12:         float bmiCalc; // Resulting BMI
 13:         char quitCmd;  // Indicates quit/continue

 15:         weightVal = 0;
 16:         heightVal = 0;
 17:         quitCmd = 'a';

 19:         while (quitCmd != 'q')
 20:         {
 21:             try
 22:             {
 23:                 // Get user data
 24:                 System.out.print("Enter weight (in pounds): ");
 25:                 weightVal = scnr.nextInt();

 27:                 // Error checking, non-negative weight
 28:                 if (weightVal < 0)
 29:                 {
 30:                     throw new Exception("Invalid weight.");
 31:                 }

 33:                 System.out.print("Enter height (in inches): ");
 34:                 heightVal = scnr.nextInt();

 36:                 // Error checking, non-negative height
 37:                 if (heightVal < 0)
 38:                 {
 39:                     throw new Exception("Invalid height.");
 40:                 }

 42:                 // Calculate BMI and print user health info if no input error
 43:                 // Source: http://www.cdc.gov/
 44:                 bmiCalc = ((float) weightVal
 45:                            / (float)(heightVal * heightVal)) * 703.0f;

 47:                 System.out.println("BMI: " + bmiCalc);
 48:                 System.out.println("(CDC: 18.6-24.9 normal)");
 49:             }
 50:             catch (Exception excpt)
 51:             {
 52:                 // Prints the error message passed by throw statement
 53:                 System.out.println(excpt.getMessage());
 54:                 System.out.println("Cannot compute health info.");
 55:             }

 57:             // Prompt user to continue/quit
 58:             System.out.print("\nEnter any key ('q' to quit): ");
 59:             quitCmd = scnr.next().charAt(0);
 60:         }
 61:     }
 62: }