java - 带有继承的 Java 中的 NullPointerException
问题描述
我正在编写一个程序来模拟身体活动下的人体温度。我写了一个广泛的“隔间”类,如下所示:
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
和其他人一样。(也是构造函数)
推荐阅读
- c# - 如何使用 Azure ClientApplication 令牌向 Microsoft Teams 写入消息
- pagespeed-insights - 移动和桌面体验之间的 Google PageSpeed Insights“实验室数据”速度截然不同?
- c# - 使用 c# 安装后从程序和功能中隐藏 MS Office 加载项
- c# - 从 8000 到 44100 kHz 重新采样 NAudio WaveIn 麦克风输入
- amazon-web-services - 使用 AWS S3/Lambda 动态调整图像大小
- r - 过滤任何包含 Inf 的行
- python-3.x - 我无法在 vim 中运行 python3 程序
- java - 通过 AWS Nat Gateway 的连接问题
- python - 如何通过 UDP 使用 Python 将数据从远程机器(客户端)发送到本地机器(服务器)?
- c# - .NET JWT 实现接受过期令牌