我在下面的行(第9行)playlist1.firstSong = song;
行中收到nullPointerException錯誤。有任何想法嗎?Instanciate類中的類NullPointerException
Playlist類:
public class Playlist {
Scanner console = new Scanner(System.in);
private Playlist playlist1=null, playlist2=null;
private Song firstSong;
private Song secondSong;
private Song thirdSong;
public void setSong(Song song) {
if (song != null) {
if (playlist1.firstSong == null) {
playlist1.firstSong = song;
System.out.println("The song has been added to the playlist.");
}
else if (playlist1.secondSong == null) {
playlist1.secondSong = song;
System.out.println("The song has been added to the playlist.");
}
else if (playlist1.thirdSong == null) {
playlist1.thirdSong = song;
System.out.println("The song has been added to the playlist.");
}
else {
System.out.println("This playlist is currently full with 3 songs. Please delete a song before attempting to add a new one.");
}
}
}
addSongToPlaylist方法:
private void addSongToPlaylist() {
if (songCount <=3) {
System.out.println("Please enter the number of the song you'd like to be added to the playlist.");
System.out.println("");
database.Display();
int songNumber;
songNumber = console.nextInt();
switch (songNumber) {
case 1:
playlist.setSong(database.getSong(1));
break;
case 2:
playlist.setSong(database.getSong(2));
break;
case 3:
playlist.setSong(database.getSong(3));
break;
case 4:
playlist.setSong(database.getSong(4));
break;
default:
System.out.println("Please enter a valid song number.");
break;
}
songCount++;
}
getSong方法:
public Song getSong(int songNumber) {
if (songNumber == 1){
return song1;
}
else if (songNumber == 2){
return song2;
}
else if (songNumber == 3){
return song3;
}
else if (songNumber == 4){/
return song4;
}
else {
return song1;
}
}
任何幫助將非常感激,謝謝!
@StephenC我正在上傳代碼,等一下。對於初學者,我想表明這比繼續使用playlist1和playlist2更合適。 – Mekap
我需要有2個播放列表,用戶可以將歌曲存入。所以我不需要playlist1和playlist2對象? – Lachie
@Lachie你可以有2個同一個類的實例! (這是「公安條例」的權力);我編輯了我的代碼,以便看到我在說什麼。 – Mekap