我正在制作一个带有单独测试主体的简单BMI计算器。我在尝试编译时不断收到“float is not dereferenced”消息。我对编码我做错了什么感到相对较新?
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());
}
}
答案 0 :(得分:1)
你不能说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
- 我建议您使用@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
实例中只支持一个高度和一个质量)。
答案 1 :(得分:0)
float
不是一个对象,甚至它的对象Float
也不知道这个方法pow()
。
试试Math.pow()。