bmi计算器错误浮点数无法解除引用

时间:2015-11-01 19:11:28

标签: java

我正在制作一个带有单独测试主体的简单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());
    }
}

2 个答案:

答案 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()