import java.util.Scanner; /* Java program that computes (and reports) body mass index (BMI) values for ** a particular height and the weights within a range beginning at some ** specified lower bound up to some specified upper bound, and increasing by ** some specified interval. ** ** This version improves upon the previous one by using calls to ** System.out.printf() to produce as output a table whose columns ** are nicely aligned. ** ** The main purposes are to illustrate the use of Java's for-loop construct ** and reading input using a Scanner object. */ public class BMICalculatorApp6 { private static Scanner keyboard; // for reading input from the keyboard private static int height; // height in inches (input) private static int lowWeight; // lower bound weight (in pounds) (input) private static int highWeight; // uppper bound weight (in pounds) (input) private static int weightGap; // gap between weights (in pounds) (input) private static double bmi; // BMI value (output) private static int weight; // weight in pounds (loop control variable) public static void main(String[] args) { // Create a Scanner object and enable it to read input entered at the keyboard. keyboard = new Scanner(System.in); System.out.print("Enter height (in inches): "); // Read input value entered at the keyboard, interpreting it as a value of // type int; then place that value into the 'height' input variable. height = keyboard.nextInt(); System.out.print("Enter bottom weight (in pounds): "); lowWeight = keyboard.nextInt(); System.out.print("Enter top weight (in pounds): "); highWeight = keyboard.nextInt(); System.out.print("Enter weight gap (in pounds): "); weightGap = keyboard.nextInt(); printColHeadings(); for (weight = lowWeight; weight <= highWeight; weight = weight + weightGap) { reportBMIValue(); } } /* Reports the BMI value corresponding to the values in the global variables ** 'height' and 'weight'. */ private static void reportBMIValue() { computeBMI(); // Print the values of 'height' and 'weight', each right-justified in a // field of width 6 followed by a space. Then print the value of 'bmi' // in a field of width five with two digits after the decimal point. // Then print a newline character (to skip to next line). System.out.printf("%6d %6d %5.2f\n", height, weight, bmi); } /* Assigns to global variable 'bmi' the BMI value computed from the values ** in global variables 'height' and 'weight'. */ private static void computeBMI() { // Conversion factor needed to convert result of BMI formula when height // and weight are measured in inches and pounds rather than in meters // and kilograms, respectively. final int UNIT_CONVERSION_FACTOR = 703; bmi = UNIT_CONVERSION_FACTOR * ((double)weight / (height * height)); } private static void printColHeadings() { System.out.printf("%6s %6s %3s\n", "Height", "Weight", "BMI"); System.out.println("------ ------ -------"); } }