[英]bmi calculator error float cannot be dereferenced
我正在制作一个带有单独测试主程序的简单 BMI 计算器。 当我尝试编译时,我不断收到“浮动无法取消引用”的消息。 我对编码比较陌生,我做错了什么?
public class BMI {
private String name;
private static float height; //meters
private static float mass; //kilograms
public BMI(String n, float h, float m) {
name = n;
height = h;
mass = m;
}
public static float getBMI() {
return (mass / height.pow(2));
}
public String toString() {
return (name + "is" + height + "tall and is " + mass + "and has a BMI of" + getBMI());
}
}
您不能说height.pow(2)
(因为float
是一个原始类型,并且因为该功能在Math
实用程序类中)。 你可以使用Math.pow(double, double)
像
return (mass / Math.pow(height, 2));
或使用简单的乘法(因为 n 2 == n * n)
return (mass / (height * height));
此外,在toString
我更喜欢String.format(String, Object...)
不是创建许多临时String
(s) - 我建议您使用@Override
注释来提供额外的编译时安全性。 就像是,
@Override
public String toString() {
return String.format("%s is %.2f tall, has mass of %.2f "
+ "and a BMI of %.2f", name, height, mass, getBMI());
}
static
private static float height; //meters
private static float mass; //kilograms
几乎肯定应该是
private float height; //meters
private float mass; //kilograms
因为否则它们是全局的(在任意数量的BMI
实例中只支持一个高度和一个质量)。
float
不是一个对象,甚至它的对象对应物Float
也不知道这个方法pow()
。 试试Math.pow() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.