I've tried looking at posts on this issue but am still having some trouble with this error in my code. So in the fourth line, I create an instance variable called SongDatabase
to access the SongDatabase
class. But when I get down to the line, SongDatabase.addNewSong();
under case 1
, I get a java.lang.NullPointerException: null error.
Interface class:
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 class:
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.");
}
}
I've stepped through the debugger and I know that the instance variable, SongDatabase = null, which is probably causing the error? I previously had a line
SongDatabase SongDatabase = new SongDatabase();
SongDatabase.addNewSong();
instead, but I realised this was creating a new SongDatabase object everytime and wiping what I had stored in there so I had to change it. I'd really appreciate a solution because I have no clue, thanks!