This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


3年前关闭。





我尝试查看有关此问题的帖子,但是我的代码在此错误上仍然遇到一些麻烦。因此,在第四行中,我创建了一个名为SongDatabase的实例变量来访问SongDatabase类。但是当我下到SongDatabase.addNewSong();下的case 1行时,我得到了java.lang.NullPointerException:空错误。

接口类:

public class Interface
{
    Scanner console = new Scanner(System.in);
    private SongDatabase SongDatabase;

    public static void main(String[] args) {
        Interface intFace = new Interface();
        intFace.run();
    }

    private void run() {
        switch (userInput) {
        case 1:
            SongDatabase.addNewSong();
            break;
        case 2:
            SongDatabase.removeSong();
            break;
        case 3:
            SongDatabase.sortSongs();
            break;
        default:
            System.out.println("Please enter a valid number.");
            break;

    }
}


SongDatabase类:

public class SongDatabase {
    Scanner console = new Scanner(System.in);
    private Song song1, song2, song3, song4;

public void addNewSong() {
        if (song1 == null) {
            song1 = getFromUser();
        }
        else if (song2 == null) {
            song2 = getFromUser();
        }
        else if (song3 == null) {
            song3 = getFromUser();
        }
        else if (song4 == null) {
            song4 = getFromUser();
        }
        else {
        System.out.println("The database is currently full. Please delete a song before adding a new one.");
       }
    }


我已经调试了整个调试器,并且知道实例变量SongDatabase = null,这可能是导致错误的原因吗?我以前有一条线

SongDatabase SongDatabase = new SongDatabase();
SongDatabase.addNewSong();


相反,但是我意识到这是每次都创建一个新的SongDatabase对象,并擦除我在那里存储的内容,因此我不得不对其进行更改。我真的很感谢一个解决方案,因为我不知道,谢谢!

最佳答案

您不应该为实例字段提供与该类相同的名称,因为这会导致Variable shadowing-维基百科说(部分)当在某个范围(决策块,方法或内部类)中声明的变量具有与在外部作用域中声明的变量同名。在标识符(名称,而不是变量)级别,这称为name masking。您可以在声明时定义引用,例如

private SongDatabase songDatabase = new SongDatabase();


然后像

private void run() {
    switch (userInput) {
    case 1:
        songDatabase.addNewSong();
        break;
    case 2:
        songDatabase.removeSong();
        break;
    case 3:
        songDatabase.sortSongs();
        break;
    default:
        System.out.println("Please enter a valid number.");
        break;
    }
}

10-08 00:49