【发布时间】:2015-05-28 17:07:36
【问题描述】:
我正在尝试让歌曲添加和删除功能适用于假设歌曲数据库的假设播放列表。
我第一次调用deleteSong() 函数从播放列表对象中删除一首歌曲时它工作正常。我第二次调用该函数时,在选择要从中删除歌曲的播放列表的索引时,它会尝试运行 selectSong() 函数,在该函数中它启动 for 循环以打印每首歌曲,但显然 songs[] 数组已满空值,或者至少元素 0 是空值,因为它在第一次迭代 (i = 0) 时抛出 NullpointerException。
logicalSize 变量很容易解释。它跟踪数组中有多少实际初始化的 Song 对象。
注意:这基本上是为我的播放列表对象(添加和删除播放列表)制作相同功能的复制/粘贴代码,我没有遇到这个问题。
方法如下:
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--;
}
添加歌曲的代码:
public void addSong(Song song)
{
songs[logicalSize] = new Song();
songs[logicalSize]= song;
logicalSize++;
songCount++;
}
selectSong() 函数:
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;
}
【问题讨论】:
-
也许添加输出会有所帮助。
-
请将堆栈跟踪添加到您的问题中。
-
我知道我不会提供帮助,但您是否尝试过在代码中设置断点并单步执行?
标签: java arrays nullpointerexception