Skip to content
Advertisement

How to implement Body Mass Index (BMI)in Java

My problem is how can I implement without the Scanner method and with Math.round and Math.pow?

Here is my code:

import java.util.Scanner;
    public class BMI{
       public static void main(String args[]) {
          Scanner sc = new Scanner(System.in);
          System.out.print("Input weight in kilogram: ");
          double weight = sc.nextDouble();
          System.out.print("nInput height in meters: ");
          double height = sc.nextDouble();
          double BMI = weight / (height * height);
          System.out.print("nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
       }
    }

My another idea was It is only for a certain value. In my case with a weight of 75.0 and size 178.0

public static void main(String args[]) {

    double weight = 75.0;
    double height = 178.0;

    double BMI = weight / (height * height);
    System.out.print("nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
 }

Advertisement

Answer

It’s up to developer to choose how to initialize parameters.
If don’t want to use scanner the simple way is just add directly.
Initialize can also come from various data-sources: database, file (xml,text), web-service, etc.
For school purpose maybe you could try to build a BMI class and use constructor to pass whatever parameters may want.
Advantage to have a constructor with parameters is that you can build various BMI instances with different result(based on params), not just have only 1 result in for all the class-instances (due to the fact the input is the same).

eg:

public class BMI 
{
    double BMI;
    public BMI(double weight,double height )
    {
        this.BMI = weight / (height * height);
    }
    
    public String toString()
    {
        return "nThe Body Mass Index (BMI) is " + this.BMI + " kg/m2";
    }
    
    public static void main(String args[])
    {
        BMI test1 = new BMI(100,1.90);
        BMI test2 = new BMI(68.77,1.60);
        System.out.println(test1);
        System.out.println(test2);
    }
}

Output:

The Body Mass Index (BMI) is 27.70083102493075 kg/m2
The Body Mass Index (BMI) is 26.863281249999993 kg/m2
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement