How to Calculate BMI in Java

The challenge

BMI stands for Body Mass Index and is a value derived from the mass and height of a person. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed in units of kg/m², resulting from mass in kilograms and height in metres. Wikipedia

Write function BMI that calculates body mass index (bmi = weight / height ^ 2).

if bmi <= 18.5 return “Underweight”

if bmi <= 25.0 return “Normal”

if bmi <= 30.0 return “Overweight”

if bmi > 30 return “Obese”

Test cases

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void testBMI() {
        assertEquals("Underweight", Calculate.bmi(50, 1.80));
        assertEquals("Normal", Calculate.bmi(80, 1.80));
        assertEquals("Overweight", Calculate.bmi(90, 1.80));
        assertEquals("Obese", Calculate.bmi(100, 1.80));
    }
    @Test
    public void testRandom() {
    System.out.println("100 Random tests");
    java.util.Random r = new java.util.Random();
          for(int i = 0; i < 99; i++) {
          double randomW = 40+r.nextDouble()*80;
          double randomH = r.nextDouble()+0.50*2.23;
          assertEquals(this.b(randomW, randomH), Calculate.bmi(randomW, randomH));
          }
    }
    
    private static String b(double w, double h) {
    double bmi = w/(h*h);
    return bmi>30.0 ? "Obese" : bmi<=30.0 && bmi>25.0 ? "Overweight" : bmi<=18.5 ? "Underweight" : "Normal";
  }
}

The solution in Java

Option 1:

import java.lang.*;

public class Calculate {
  public static String bmi(double weight, double height) {
    // Use `Math.pow` to get the power of the height
    double bmi = weight / Math.pow(height, 2);
    
    if (bmi<=18.5) return "Underweight";
    if (bmi<=25.0) return "Normal";
    if (bmi<=30.0) return "Overweight";
    if (bmi>30) return "Obese";
    
    // We should never get here..
    return "";
  }
}

Option 2:

public class Calculate {
  public static String bmi(double weight, double height) {
    double bmi = weight/(height*height);
    return bmi <= 18.5 ? "Underweight": bmi <=25.0 ? "Normal" : bmi<=30.0 ? "Overweight" : "Obese";
  }
}
Tags:
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments