简体   繁体   English

“线程“ main”中的异常java.lang.NullPointerException”

[英]“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. 我已经给了它6张专辑,现在我正在尝试打印标题。 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. 该错误出现在第21行,但我不确定这意味着什么。 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): 甚至更简单(如@entonio所指出的):

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. 您的albums[0]尚未创建,因此尝试访问其year字段(甚至用于写作)会导致NPE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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