user3094477 user3094477 - 2 months ago 11
Java Question

Variable bmr might not have been initialized

import java.util.Scanner;

public class BMR

{
public static void main(String[] args)

{
//object to use the keyboard input methods

Scanner in = new Scanner(System.in);



//ask the user to provide input

System.out.print("Enter your name: ");

String name = in.next();

System.out.print("Gender (M of F): ");

String gender = in.next();

System.out.print("Enter your age: ");

String age = in.next();

System.out.print("Height in inches: ");

String height = in.next();

System.out.println("Weight in pounds: ");

String weight = in.next();

System.out.println();

System.out.println();




//convert measurements to metric units

double ageNum = Double.parseDouble(age);

double heightNum = Double.parseDouble(height);

double weightNum = Double.parseDouble(weight);

double heightCm = heightNum * 2.54;

double weightKilo = weightNum * 0.453592;



//calculate the BMR for males or females

double bmr;

if ( gender == "M" )
bmr = (13.397 * weightKilo) + (4.799 * heightCm) - (5.677 * ageNum) + 88.362;

else if ( gender == "F" )
bmr = (9.247 * weightKilo) + (3.098 * heightCm) - (4.330 * ageNum) + 447.593;

else
System.out.println("Please enter either M or F. I apologize for the gender binary.");

//display output

System.out.println("Calculate Your Basal Metabolism");

System.out.println();

System.out.println("Name: " + name);

System.out.println("Gender: " + gender);

System.out.println("Age: " + age);

System.out.println("Weight (kg): " + weightKilo);

System.out.println("Height (cm): " + heightCm);

System.out.println("Basal Metabolic Rate: " + bmr + " calories per day");





}
}


I had to write this code for my online class to calculate the someone's Basal Metabolic rate. Every time I run it I get an error saying that the variable bmr might not have been initialized. But I did initialize it in my conditional statements. What am I doing wrong? Thanks!

Answer

double bmr; change to double bmr=0;

you did not initialize your local variable.

There is another mistake in your code. gender is a String and you are comparing String using == it is wrong. you should use equals()

use

if("M".equals(gender))

instead of

if ( gender == "M" )
Comments