I'm trying to get song add and delete functionality working for hypothetical playlists for a hypothetical song database.
The first time I call the deleteSong()
function to delete a song from a Playlist object it works fine. The second time I call the function, upon selecting the index of the playlist to delete a song from, it attempts to run the selectSong()
function where it initiates the for loop to print each song, but apparently the songs[]
array becomes full of nulls, or at least element 0 is a null, as it throws the NullpointerException
on the first iteration (i = 0
).
The logicalSize
variable is pretty self explanatory. It tracks how many actual initialized Song objects there are in the array.
Note: This is basically copy/pasted code from making the same function for my Playlist objects (adding and deleting playlists) and I haven't encountered this issue.
Here are the methods:
public void deleteSong(int index){
System.out.println("[INFO] Deleting the selected song...");
Song[] tempSongs = new Song[songs.length-1];
tempSongs[tempSongs.length-1] = new Song();
if (index+1 > songs.length-1){
System.out.println("[INFO] Song item is last element.");
for (int i=0;i<tempSongs.length;i++){
tempSongs[i] = songs[i];
}
} else {
//songs[index+1] = songs[index];
for (int i=index;i<tempSongs.length;i++){
if (i == index){
System.out.println("[INFO] Song: skip index to remove");
} else {
tempSongs[i] = songs[i+1];
}
}
}
songs = tempSongs;
logicalSize--;
}
code for adding a song:
public void addSong(Song song)
{
songs[logicalSize] = new Song();
songs[logicalSize]= song;
logicalSize++;
songCount++;
}
selectSong() function:
public int selectSong()
{
Scanner menu = new Scanner(System.in);
for (int i=0;i<logicalSize;i++){
System.out.println("[" + i + "] Title: " + songs[i].getName() + " Artist: " + songs[i].getArtist());
}
System.out.println("Select a song by entering its song number (0, 1, 2...).");
int songChoice = menu.nextInt();
return songChoice;
}