0

I'm trying to add a song from one class to a second Album class. But i'm getting "Exception in thread "main" java.lang.NullPointerException" error. I'm new to java and any help is appreciated.

public class Album {
// class behaviours
private String albumName;
private Song[] songs;
private int totalAlbumLength;
private int numSongs;

// constructor
public Album(String albumName) {
    setAlbumName(albumName);
}


// special setters: adding new song
public void addSong(Song newSong) {
    this.songs[this.numSongs] = newSong;
    this.numSongs++;
}

public void addSong(String songName, String artistName, int minutes, int seconds) {
    Song newSong = new Song(songName, artistName, minutes, seconds);
    addSong(newSong);

}

Song class

public class Song {
// class behaviours
private String songName = "";
private String artistName = "";
private int songLength = 0;

// constructors
public Song(String songName, String artistName, int minutes, int seconds) {
    setSongName(songName);
    setAtristName(artistName);
    setSongLength(minutes, seconds);
}

public Song(String songName, String artistName, int seconds) {
    setSongName(songName);
    setAtristName(artistName);
    setSongLength(seconds);
}

1 Answers1

0

You never initialized the array private Song[] songs;. Initialize it like private Song[] songs = new Song[size];

If you are uncertain about number of elements use ArrayList<Song>

Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23