2

I'm trying to write a program to create a media object, I created the Cassette class which inherits from Audio which inherits from Media. I'm getting a null pointer exception and I have been trying for hours to fix it but I have no idea why it's being thrown. I appreciate your help in advance, thank you.

In my application class I initiate the following:

static Media[] collection = new Media[100];

And later on in the code I try to create a new Cassette object but it gives me the said null pointer exception. The code I have is:

  collection[collection[0].getNumItems()] = new Cassette(cTitle, cMajorArtist, cPlayingTime, cNumPlays, cNumGroupMembers, cGroupMembers, pArtist, cNumSongs, cSongs);

All of the items being passed into the Cassette are all user input data. It compiles fine but it's just when I run it that I get an error.

EDIT
Here is the numItems value in my media class.
static int numItems = 0;
And the method to return the number of items:

public int getNumItems()
   {
      return numItems;
   }

Thanks.

nviens
  • 427
  • 2
  • 4
  • 18

1 Answers1

0

I suggest you use a Collection like ArrayList. With the diamond operator that would look something like,

static List<Media> collection = new ArrayList<>();

Then you can use List#add(E)

collection.add(new Cassette(cTitle, cMajorArtist, cPlayingTime, 
    cNumPlays, cNumGroupMembers, cGroupMembers, pArtist, cNumSongs, cSongs));

Edit If you want to use the array type, then this

collection[collection[0].getNumItems()]

Should be

collection[Media.getNumItems()]

To call the static getNumItems() in Media. Which should be

public static int getNumItems()
{
  return numItems;
}
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thank you for the array answer, it saved me from having to rewrite my code. It did the trick! Thank you! – nviens Oct 21 '14 at 01:53