[英]Simple java music database with NullPointerException
我是第一年的计算机科学,第一学期的任务是用java设计一个简单的音乐数据库。 我使用3个类,Interface(处理所有用户输入/输出),Song(存储艺术家,名称,持续时间和文件大小)和数据库(存储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");
}
}
有人可以帮我解决这个问题吗?
if (a==null) setData(a,artist,name,duration,fileSize);
如果a == null
,则使用a
作为第一个参数(为null
)调用setData
。
现在,在setData
你可以:
sin.setArtist(artist);
其中sin
是第一个参数。 这就像写作:
null.setArtist(artist)
,当然......抛出一个NPE。
附加说明:我建议您遵循Java命名约定 。 在您阅读完之后,您可能希望将类名更改为以大写字母开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.