首页 > 解决方案 > 无法存储到对象数组,因为“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;

    }

}

标签: javaarraysoopobject

解决方案


在创建要插入的对象之前,您必须分配数组的大小。现在您正在声明一个没有大小的数组,并且您正在尝试将一个共享对象添加到整个数组中。

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....);

}

我希望我能够解决你的问题。


推荐阅读