java - 无法存储到对象数组,因为“this.share”为空
问题描述
我必须创建一个对象数组,但我不知道为什么它每次都实例化为 null。类的构造函数不是空的,它有 2 个参数,所以我不能用new Share()
.
public class Portfolio {
private Share[] share;
private int noShares = 0;
public Portfolio() {} //constructor
public void addShare(Share s) {
share[noShares++] = new Share(s.getValue(), s.getCompany());
}
我也试过这个,但它给出了同样的错误
share[noShares].setValue(s.getValue));
share[noShares++].setCompany(s.getCompany);
这是最后一种方法
public double computeSum() {
int sum = 0;
for(int i = 0; i < noShares; i++) {
sum += share[noShares].getValue();
}
return sum;
}
}
解决方案
在创建要插入的对象之前,您必须分配数组的大小。现在您正在声明一个没有大小的数组,并且您正在尝试将一个共享对象添加到整个数组中。
public class Portfolio {
//Declare and initialize the Array
private Share[] share = new Share[Amount of share objects that you want to save];
//Now you can add the actual objects in the Array
Share[index] = new Share(int x, int y....);
}
我希望我能够解决你的问题。
推荐阅读
- android - OneSignal:获取 FCM 令牌的未知错误
- javascript - 在底部插入 Adsense 广告作为粘性广告
- javascript - 如何检查视频是否已上传或更新?
- c# - 切换到不同的表单(C#、Windows 表单)时,列表的元素不会更新
- ios - 单击后退按钮并更新状态数据后,swiftui子视图重新出现
- excel - 如何从工作表中获取价值,然后根据匹配的 ID 在 Excel 中的另一张工作表上显示
- html - React map 正在复制 DOM 元素
- keras - keras 序列模型中的编译步骤抛出错误“ValueError:layersequential_9 的输入 0 与该层不兼容:
- go - 如何安装谷歌云视觉api?
- c# - [DllImport] 是否每次都导入整个 DLL 库?