gpt4 book ai didi

java - Java 中的 NullPointerException 与继承

转载 作者:行者123 更新时间:2023-11-30 01:41:25 25 4
gpt4 key购买 nike

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

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 ,其他的也一样。 (也是构造函数)

关于java - Java 中的 NullPointerException 与继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com