I am trying to make a BMI calculator that calls a method of a separate class to calculate the bmi, then continue in the main method. Below is my source code.
import java.util.Scanner;
public class testBMI
{
public static void main(String[] args)
{
String name;
double bmi;
String bmiClass;
char z;
Scanner readinput = new Scanner(System.in);
do
{
System.out.print("Please enter your name: ");
name = readinput.nextLine();
BMI.calculateBMI();
if (bmi < 18.5)
{
bmiClass = "(Underweight)";
}
else
if (bmi >= 18.5 && bmi <= 25)
{
bmiClass = "(Normal)";
}
else
if (bmi > 25.0 && bmi <= 30.0)
{
bmiClass = "(Overweight)";
}
else
bmiClass = "(Obese)";
System.out.println(name + ", your BMI is " +bmi+ "" +bmiClass+ ".");
System.out.print("Type Y or y to continue, or any other key to quit: ");
z = readinput.next().charAt(0);
} while (z == 'Y' || z == 'y');
}
}
And the other class:
import java.util.Scanner;
public class BMI
{
public static void calculateBMI()
{
Scanner readinput = new Scanner(System.in);
double weight;
double height;
double newWeight;
double newHeight;
double bmi;
System.out.print("Please enter your weight in pounds: ");
weight = readinput.nextInt();
System.out.print("Please enter your height in inches: ");
height = readinput.nextInt();
newWeight = weight * 0.45359237;
newHeight = height * 0.0254;
bmi = newWeight/(newHeight*newHeight);
}
}
When compiling these files I successfully compile my method class ( the second snippet ) but get 1 error on the first, which reads like this:
testBMI.java:21: error: variable bmi might not have been initialized
if (bmi < 18.5)
^
1 error
The variable bmi is obviously declared, but the initialization (actual value adding to the variable) occurs within the separate method, however, I'm not sure why the main method hasn't recognized it's initialization from the running of the second method. Please tell me what I am doing wrong.
You need to return the value of bmi in your BMI class. When you check the value of bmi in your testBMI class it's only been locally initialized in your BMI class, not your testBMI class.