java - 带有 NullPointerException 的简单 Java 音乐数据库

标签 java database null nullpointerexception

我是计算机科学专业的一年级学生,我们第一学期的作业是用 Java 设计一个简单的音乐数据库。 我使用 3 个类,接口(interface)(处理所有用户输入/输出)、歌曲(存储艺术家、名称、持续时间和文件大小)和数据库(存储 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,艺术家,姓名,持续时间,文件大小);

如果a == null,则调用setData,并将a作为第一个参数(即null) .

现在,在 setData 中,您可以:

sin.setArtist(artist); 其中 sin 是第一个参数。这就像写:

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

补充说明:我建议您关注Java Naming Conventions 。阅读本文后,您可能想要将类名更改为以大写字母开头。

关于java - 带有 NullPointerException 的简单 Java 音乐数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16249858/

相关文章:

android - 升级我的数据库

具有不确定状态的 Android CheckBox?

javascript XMLHttpRequest requestXML 为 null

java - 如何使用 NetBeans 在 Windows Java 项目中使用 HDF5

java - 在 Java 中在椭圆内循环

java - Spring、NotReadablePropertyException 和 Glassfish 版本

php - WordPress $wpdb->get_results 即使为空也会返回日期

php - MySQL数据库的基本结构

java - Java 列表中的头/尾

linux - shell Linux : grep exact sentence with NULL character