-1

I have to create an object array, but I can't figure out why it is instantiating to null every time. The class' constructor is not empty, it has 2 parameters, so I can't initialize it with 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());

    }

I have also tried this, but it gives the same error

share[noShares].setValue(s.getValue));
share[noShares++].setCompany(s.getCompany);

And this is the last method

    public double computeSum() {

        int sum = 0;

        for(int i = 0; i < noShares; i++) {

            sum += share[noShares].getValue();

        }

        return sum;

    }

}
Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158

2 Answers2

1

You have to assign the size of the Array, before you create an Object that you want to insert. Right now you are declaring an Array, without a size, and you are trying to add one Share Object to the entire array.

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

}

I hope that i was able to solve your problem.

IX0Y3
  • 68
  • 1
  • 7
0

Try:

public class Portfolio {

    private Share[] share = new Share[100]; //or whatever number of elements

}

You need to intantiate/assign memory to the array beforehand.

Manuel
  • 43
  • 7