我正在学习java但是在创建计算体重指数的方法时遇到了困难。它不接受我之前在程序中声明的实例变量,我不知道如何解决这个问题。感谢所有帮助!
代码:
import java.util.Formatter;
public class HealthRecord
{
// initialise instance variables
String first;
String last;
double height;
double weight;
public HealthRecord(String LastName, String FirstName, double height, double weight)
{
first = FirstName;
last = LastName;
height = height;
weight = weight;
}
public static void main(String args[]) {
HealthRecord record = new HealthRecord("Last", "First", 72, 150);
System.out.println("BMI="+record.getBMI());
}
// calculate BMI
public double getBMI() {
double bmi = weight / (height * height) * 703.0;
return bmi;
}
}
结果: BMI = NaN的
答案 0 :(得分:0)
更新您的构造函数,如下所示:
public HealthRecord(String LastName, String FirstName, double height, double weight)
{
first = FirstName;
last = LastName;
this.height = height;
this.weight = weight;
}
答案 1 :(得分:0)
在HealthRecord
构造函数中,您要将height
和weight
的值分配给方法参数,而不是分配给对象/实例变量。
如果要为实例变量赋值,则需要使用this
运算符,该运算符始终引用当前对象(查看here)并参考以下代码:
public HealthRecord(String first, String last,
double height, double weight) {
this.first = first;
this.last = last;
this.height = height;
this.weight = weight;
}
此外,我已将参数名称更新为first
和last
(方法参数),以便它们如上所示一致。
我建议您始终对方法参数和实例变量使用相同的变量名称(将其作为练习)&使用this.
来引用实例变量。