gpt4 book ai didi

java - 在类 NullPointerException 中实例化一个类

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:46:07 24 4
gpt4 key购买 nike

我在下面的 playlist1.firstSong = song; 行(第 9 行)中收到 nullPointerException 错误。有什么想法吗?

播放列表类:

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++;
}

获取歌曲方法:

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;
}
}

非常感谢任何帮助,谢谢!

最佳答案

因为你没有初始化播放列表对象。执行以下操作,

这样做。

   private Playlist playlist1= new PlayList(), playlist2=new Playlist(); 

代替

   private Playlist playlist1=null, playlist2=null; 

编辑:

class listMenu {
// class that contains 3 playlists object.

PlayList list1 = new Playlist(), list2 = new Playlist(), list3 = new PlayList();

addPlayList() {
// whatever your logic for addition is.
}

}

您编写代码的方式是错误的,因为。

class PlayList {
PlayList list1 = new PlayList(), list2 = new Playlist();
private Song song1 = null;
private Song song2 = null;
private Song song3 = null;

void setSong(Song song){
list1.song1 = song; // you are storing song in of list1.song field.
}
}

当尝试访问歌曲时,会再次出现NullPointerexception

class Menu{
void main(// ) {
PlayList list = new PlayList();
list.setSong(new Song());
list.getSong1.name(); // throw exception, because song is stored in the member object not in itselt.



}
}

希望你明白我的意思

关于java - 在类 NullPointerException 中实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30030371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com