I just started learning Java and I'm trying to create a simple BMI calculator using the OOP concept.
Here are my codes:
import java.util.Scanner;
class BIM
{
int weight;
double weightKG = weight * 0.45359237;
int height;
double heightMETERS = height * 0.0254;
double BMI = weightKG / (heightMETERS * heightMETERS);
public void calculateBMI()
{
System.out.print("The BMI is: " + BMI);
}
}
public class BMI
{
public static void main(String args[] ) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.print("Enter weight in pounds: ");
int weight = input.nextInt();
System.out.print("Enter height in inches: ");
int height = input.nextInt();
BIM b = new BIM();
b.calculateBMI();
}
private static void bmiCategory (double BMI)
{
if (BMI < 18.5)
{
System.out.println("Underweight");
}
else if (BMI < 25.0)
{
System.out.println("Normal");
}
else if (BMI < 30.0)
{
System.out.println("Overweight");
}
else
{
System.out.println("Obese");
}
}
}
The output of my codes:
Enter weight in pounds: 100 Enter height in inches: 50 The BMI is: NaN
Why am I getting the output NaN? and also, why is not displaying the category?
Your BIM
class does all the math, but you never pass a height
or weight
to it (and you do the math before you assign those values anywhere). First, fix BIM
. Something like,
class BIM {
public BIM(int weight, int height) {
this.weight = weight;
this.height = height;
this.weightKG = weight * 0.45359237;
this.heightMETERS = height * 0.0254;
this.BMI = weightKG / (heightMETERS * heightMETERS);
}
int weight;
double weightKG;
int height;
double heightMETERS;
double BMI;
public void calculateBMI() {
System.out.print("The BMI is: " + BMI);
}
}
Then instead of
BIM b = new BIM();
You need
BIM b = new BIM(weight, height);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments