Source of BMIExceptHandlingWithMethods.java


  1: //BMIExceptHandlingWithMethods.java

  3: import java.util.Scanner;

  5: public class BMIExceptHandlingWithMethods
  6: {
  7:     public static int getWeight(Scanner scnr) throws Exception
  8:     {
  9:         int weightParam; // User defined weight (lbs)

 11:         // Get user data
 12:         System.out.print("Enter weight (in pounds): ");
 13:         weightParam = scnr.nextInt();

 15:         // Error checking, non-negative weight
 16:         if (weightParam < 0)
 17:         {
 18:             throw new Exception("Invalid weight.");
 19:         }
 20:         return weightParam;
 21:     }

 23:     public static int getHeight(Scanner scnr) throws Exception
 24:     {
 25:         int heightParam; // User defined height (in)

 27:         // Get user data
 28:         System.out.print("Enter height (in inches): ");
 29:         heightParam = scnr.nextInt();

 31:         // Error checking, non-negative height
 32:         if (heightParam < 0)
 33:         {
 34:             throw new Exception("Invalid height.");
 35:         }
 36:         return heightParam;
 37:     }

 39:     public static void main(String[] args)
 40:     {
 41:         Scanner scnr = new Scanner(System.in);
 42:         int weightVal; // User defined weight (lbs)
 43:         int heightVal; // User defined height (in)
 44:         float bmiCalc; // Resulting BMI
 45:         char quitCmd;  // Indicates quit/continue

 47:         quitCmd = 'a';

 49:         while (quitCmd != 'q')
 50:         {
 51:             try
 52:             {
 53:                 //Get user data
 54:                 weightVal = getWeight(scnr);
 55:                 heightVal = getHeight(scnr);

 57:                 // Calculate BMI and print user health info if no input error
 58:                 // Source: http://www.cdc.gov/
 59:                 bmiCalc = ((float) weightVal /
 60:                            (float)(heightVal * heightVal)) * 703.0f;

 62:                 System.out.println("BMI: " + bmiCalc);
 63:                 System.out.println("(CDC: 18.6-24.9 normal)");
 64:             }
 65:             catch (Exception excpt)
 66:             {
 67:                 // Prints the error message passed by throw statement
 68:                 System.out.println(excpt.getMessage());
 69:                 System.out.println("Cannot compute health info.");
 70:             }

 72:             // Prompt user to continue/quit
 73:             System.out.print("\nEnter any key ('q' to quit): ");
 74:             quitCmd = scnr.next().charAt(0);
 75:         }
 76:     }
 77: }