I am trying to make an array of video games. I wanted to implement an array method that will add a new game to the array if there is an available index that is null. however when I try to implement such a method. It throws a NullPointerException.
Here is the code in the main method:
public static void main(String[] args) {
Game[] arr = new Game[3];
Game t1 = new Game("The Walking Dead", 2012, "Telltale games");
Game t2 = new Game("The Wolf Among Us", 2014, "Telltale games");
Game t3 = new Game("Half-Life 2", 2007, "Valve");
try {
arr[2].addGame(t3);
} catch(NullPointerException e) {
System.out.println("Caught NullPointer");
arr[0] = t1;
}
System.out.println(arr[0]);
}
And here is the method I have implemented in the "Game" class:
public Game addGame(Game game) {
//TODO
for(int i = 0; i < arr.length; i++) {
try {
if(arr[i] == null) {
arr[i] = game;
}
} catch(NullPointerException e) {
System.out.println("Caught exception");
arr[i] = game;
return arr[i];
}
}
return game;
}
I am very lost and I don't understand how it is throwing the nullpointerexception when I am explicitly trying to check for null to try and insert a new "Game" into the empty index. Any help is much appreciated! Thanks!