简体   繁体   中英

Simple java music database with NullPointerException

I'm first year computer science and our assignment for semester 1 is to design a simple music database in java. I'm using 3 classes, Interface(handles all user in/out), Song(stores artist, name, duration and filesize) and Database(stores 4 song objects; a,b,c,d). I can compile and run the the program fine, but when I enter the last field(fileSize) instead of a message returning the recently entered information I receive a NullPointerException, I understand this has something to do with assigning the value of null.

The code for the database class is;

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

Can anybody help me out with this?

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

if a == null you call setData with a as the first parameter (which is null ).

Now, in setData you do:

sin.setArtist(artist); where sin is the first parameter. Which is like writing:

null.setArtist(artist) , which of course.. throws an NPE.

Additional side note: I suggest you to follow Java Naming Conventions . After you'll read this, you might want to change the class name to begin with a capital letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM