0

我是计算机科学专业的一年级,我们第一学期的任务是用 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");
    }
}

有人可以帮我解决这个问题吗?

4

1 回答 1

2

if (a==null) setData(a,artist,name,duration,fileSize);

如果a == null您调用setDatawitha作为第一个参数(即null)。

现在,在setData你做:

sin.setArtist(artist);sin第一个参数在哪里。这就像写:

null.setArtist(artist),这当然..抛出一个NPE。

附加说明:我建议您遵循Java Naming Conventions。阅读完本文后,您可能希望将类名更改为以大写字母开头。

于 2013-04-27T08:16:57.770 回答