我是计算机科学专业的一年级,我们第一学期的任务是用 Java 设计一个简单的音乐数据库。我正在使用 3 个类,接口(处理所有用户输入/输出)、歌曲(存储艺术家、名称、持续时间和文件大小)和数据库(存储 4 个歌曲对象;a、b、c、d)。我可以很好地编译和运行程序,但是当我输入最后一个字段(fileSize)而不是返回最近输入的信息的消息时,我收到了 NullPointerException,我知道这与分配 null 的值有关。
数据库类的代码是;
public class songDatabase
{
song sin = new song();
private song a,b,c,d;
public songDatabase()
{
a = null;
b = null;
c = null;
d = null;
}
public void addSong(String artist, String name, double duration, int fileSize)
{
if (a==null) setData(a,artist,name,duration,fileSize);
else if (b==null) setData(b,artist,name,duration,fileSize);
else if (c==null) setData(c,artist,name,duration,fileSize);
else if (d==null) setData(d,artist,name,duration,fileSize);
}
private void setData(song sin, String artist, String name, double duration, int fileSize)
{
sin.setArtist(artist);
sin.setName(name);
sin.setDuration(duration);
sin.setFileSize(fileSize);
}
public String visconfir()
{
if (a != null) return("You have imported: "+sin.getName()+"by"+sin.getArtist()+"which is"
+sin.getFileSize()+"kB and"+sin.getDuration()+"long(mm.ss)");
else return("Error - No file imported to database memory slot a");
}
}
有人可以帮我解决这个问题吗?