【发布时间】:2015-09-04 01:31:32
【问题描述】:
我正在创建一个 BMR 计算器,并且我有一个名为 User 的类。该类包含用于计算 BMR 的所有方法,以及将用户数据(年龄、性别、体重、身高)打包在一起的构造函数。
代码是:
public class User {
int age;
String gender; // todo: use an Enum
double height; // height stored in cm, weight in kg (so if user enters in feet/lbs, conversions are done to cm/kg and *THEN* passed through to constructor below)
double weight;
double activityMultiplier; // todo: use an Enum (possibly)
int bmr;
public User(int age, String gender, double height, double weight,
double activityMultiplier) {
this.age = age;
this.gender = gender;
this.height = height;
this.weight = weight;
this.activityMultiplier = activityMultiplier;
bmr = calcBMR();
}
/**
* If user input is correct, this method will calculate the BMR value of the user given their input and measurement choices.
*
* @param None
* @return BMR Value
*/
public int calcBMR() {
int offset = gender.equals("M") ? 5 : -161;
// This is the body of the calculations - different offset used depending on gender. Conversions to kg and cm done earlier so no conversions needed here.
// The formula for male and female is similar - only the offset is different.
return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) + offset)); // This is the Miffin St-Jeor formula, calculations done in cm/kg
}
/**
* If the user selects the TDEE option, this method will be executed after the calcBMR() method.
* A value from the calcBMR() method will be passed down to this method, and is multiplied
* by the activity level parameter passed into this method.
*
* @param bmr (output from calcBMR() method
* @return TDEE Value
*/
public int calcTDEE(int bmr) {
return (int) Math.round(calcBMR() * activityMultiplier);
}
}
我担心的是我不确定我在构造函数 (bmr = calcBMR()) 中初始化 bmr 值的方式是否正确。我无法计算 bmr,直到用户的年龄、性别、身高和体重被记录并存储在变量中(这是上面 5 行所做的)。这种编程结构好吗? IE。当一个 User 对象被创建时,年龄、性别、身高和体重被存储在变量中,THEN在构造函数中调用一个方法来计算和存储另一个值。
有没有更好的方法来做到这一点?如果没有,我需要做this.bmr = calcBMR() 还是bmr = calcBMR() 可以吗?
请注意,用户对象是在单独的类中创建的。我主要困惑的原因是因为我没有将 bmr 参数传递给构造函数,而是使用方法返回值来初始化实例变量的值。
【问题讨论】:
标签: java variables constructor