简体   繁体   中英

“Exception in thread ”main“ java.lang.NullPointerException”

I'm trying to run a program that will, if all goes well, be able to take a year and return the title of an album released in that year. I've given it 6 albums already and I'm now trying to actually print a title. I've fixed a few pretty frustrating errors, but this is one I've not seen before. The error appears at line 21, but I'm not sure what it means. Can anyone help?

package songselector;

import java.util.Scanner;

public class Main {
    public class Album
    {
int year; String title;
public Album () {
this.year = 0; this.title = null;
        }
public Album (int year, String title) {
this.year = year; this.title = title;
     }
    }

   class CAKE {
Album[] albums;
public CAKE () {
albums = new Album[6];
albums[0].year = 1994; albums[0].title = "Motorcade Of Generosity";
albums[1].year = 1996; albums[1].title = "Fashion Nugget";
albums[2].year = 1998; albums[2].title = "Prolonging The Magic";
albums[3].year = 2001; albums[3].title = "Comfort Eagle";
albums[4].year = 2004; albums[4].title = "Pressure Chief";
albums[5].year = 2011; albums[5].title = "Showroom of Compassion";
     }

public void printAlbum (int y) {
System.out.println (albums[y].title);
    }

    }

    public static void main(String[] args) {
        new Main().new CAKE().printAlbum (0);
    }
}

It means that you are trying to access / call a method on an object which is null. In your case, you initialized the array of Albums, but didn't initialize each of the albums in the array.

You need to initialize each album in the array:

albums = new Album[6];
albums[0] = new Album();
albums[0].year = 1994; 
albums[0].title = "Motorcade Of Generosity";
...

Or even simpler (as @entonio pointed out):

albums = new Album[6];
albums[0] = new Album(1994, "Motorcade Of Generosity");
albums[1] = new Album(1996, "Fashion Nugget");
...

Since you have a proper constructor.

One more thing: don't call more than one method in each line, it will help you debugging.

When you allocate an array of objects, it's filled with null values. You need to create objects to fill them. Your albums[0] wasn't created, so trying to access its year field (even for writing) results in a NPE.

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