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");
}
}
我必須爲我的在線課程編寫此代碼來計算某人的基礎代謝率。每次運行它時,我都會收到一個錯誤消息,說變量bmr可能沒有被初始化。但我在條件語句中初始化了它。我究竟做錯了什麼?謝謝!變量bmr可能尚未初始化
您需要初始化bmr,如錯誤消息所示,您只聲明瞭it.Inialialize爲double bmr = 0.0; – Suman
搜索錯誤:[\ [java \]變量可能尚未初始化](http://stackoverflow.com/search?q=%5Bjava%5D+variable+might+not+have+been+initialized)和你會發現*很多*重複。其實,甚至不搜索。只要看看相關的問題 - 不妨現在就去做,因爲在提出問題時顯然忽略了這些建議。 – user2864740