Here's a detailed explanation and corrected answer you can post on StackOverflow:
You're experiencing the issue because of a common mistake in your constructor and how you're calling the BMI calculation method. Let's walk through it step-by-step.
In your Person
constructor:
public Person(String userFirstName, double userHeightInches, double userWeightPounds) {
this.firstName = firstName;
this.heightInches = heightInches;
this.weightPounds = weightPounds;
}
You're using the wrong variable names inside the constructor. Instead of using userFirstName
, userHeightInches
, and userWeightPounds
, you're using firstName
, heightInches
, and weightPounds
which are the class fields. As a result, you're assigning null
and 0.0
values to your object fields.
โ Fix it like this:
public Person(String userFirstName, double userHeightInches, double userWeightPounds) {
this.firstName = userFirstName;
this.heightInches = userHeightInches;
this.weightPounds = userWeightPounds;
}
In your displayBMI()
method, you're passing 0
for both height and weight:
double userWeightPounds = 0;
double userHeightInches = 0;
double BMI = anyPerson.calculateBMI(userWeightPounds, userHeightInches);
So you're calling the calculateBMI()
method with zeros, even though the anyPerson
object already has the correct height and weight.
โ You have two options to fix this:
calculateBMI()
to use object fields:Update the Person
class method to:
public double calculateBMI() {
return (this.weightPounds / (this.heightInches * this.heightInches)) * 703;
}
And then call it in displayBMI()
like this:
double BMI = anyPerson.calculateBMI();
double userWeightPounds = anyPerson.getWeightPounds();
double userHeightInches = anyPerson.getHeightInches();
double BMI = anyPerson.calculateBMI(userHeightInches, userWeightPounds);
But Option 1 is cleaner and more object-oriented.
Fix constructor variable names.
Use the actual object values to calculate BMI.
Optionally, update calculateBMI()
to not require parameters.
toString()
If you want to include BMI in the output string, modify your toString()
like this:
@Override
public String toString() {
double bmi = calculateBMI();
return this.firstName + " weighs " + this.weightPounds + " lbs and is " + this.heightInches +
" inches tall. Your BMI is " + String.format("%.2f", bmi);
}
Input:
John
70
150
Output:
John weighs 150.0 lbs and is 70.0 inches tall. Your BMI is 21.52
Healthy
I have also created BMI calculator, you can check here