我正在编写一个程序来模拟体育锻炼下的人体温度。我编写了一个宽泛的“隔间”类,如下所示:

public class compartment {

    public float height;
    public float weight;
    public float age;
    public float mrest;

    public float HR;
    public float VO2;
    public float [] temps;
    public float [] K = {54.29f, 41.76f, 15.87f, 41.76f, 20.88f};

    private float BF;
    private float T;
    private float H;

    private float hCap;
    private float dnsty;

    public compartment(float height, float weight, float age, float HR, float VO2, float [] temps) {

        height = this.height;
        weight = this.weight;
        age = this.age;
        mrest = 1.5f * weight;

        HR = this.HR;
        VO2 = this.VO2;
        temps = this.temps;
    }

    // GETTERS
    public float getBF() {
        return BF;
    }
    public float getT() {
        return T;
    }
    public float getH() {
        return H;
    }
    public float gethCap() {
        return hCap;
    }
    public float getDnsty() {
        return dnsty;
    }

    // SETTERS
    public void setBF(float BF) {
        BF = this.BF;
    }
    public void setT(float T) {
        T = this.T;
    }
    public void setH(float H) {
        H = this.H;
    }
    public void sethCap(float hCap) {
        hCap = this.hCap;
    }
    public void setDnsty(float dnsty) {
        dnsty = this.dnsty;
    }
}


然后,我编写了一个子类,它是主体的核心部分,如下所示:

public class core extends compartment{

    public void calc() {

        // Setting up constants
        int n = 0;
        float H = 0.824f;
        setDnsty(1.1f);
        sethCap(51);

        // Calculating blood flow
        float pctMaxHr = HR/(220-age);
        float dubois = (float) (2.0247 * Math.pow(height, 0.725) * Math.pow(weight, 0.425));
        float pctMaxBf = (float) ((pctMaxHr <= 39) ? 100:100 - 1.086*(pctMaxHr-39));
        float maxBf = (float) (0.92*dubois*3.2);
        float bf = (pctMaxBf)*(maxBf);

        // Calculating heat production
        setH(mrest*H);

        // Calculating derivative
        float Q = getH() - (K[n]*(temps[n] - temps[n+1])) - (bf*getDnsty()*gethCap()*(temps[n] - temps[5]));

        // Adjusting the temperature
        float T = temps[n] + Q;
        setT(T);
    }

    public core(float height, float weight, float age, float HR, float VO2, float[] temps) {
        super(height, weight, age, HR, VO2, temps);
        calc();
    }

}


但是,当我尝试创建“核心”对象时,我得到了Java NullPointerException

Exception in thread "main" java.lang.NullPointerException
    at core.calc(core.java:22)
    at core.<init>(core.java:32)
    at model.main(model.java:7)


22号线是

float Q = getH() - (K[n]*(temps[n] - temps[n+1])) - (bf*getDnsty()*gethCap()*(temps[n] - temps[5]));


用System.out.println进行一些调试,似乎没有一个变量正确地实例化,例如当我打印可变的mrest或height时,它们都显示为0.0

我是否错过了继承的基本属性?我究竟做错了什么?谢谢。

最佳答案

这是因为set值分配做错了。它应该是this.dnsty = dnsty,其他应该相同。 (也是构造函数)

09-05 03:43