-2

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!

Ty Strong
  • 13
  • 1
  • 2
  • 1
    `Game[] arr = new Game[3];` creates an empty array, so each element in the array is `null`. You need to assign a value to the array, ie `arr[0] = new Game("The Walking Dead", 2012, "Telltale games");`. You should also check each element to determine if it's been assigned, ie `arr[0] != null` before trying to access it – MadProgrammer Apr 10 '21 at 23:59

1 Answers1

0

I would suggest instead using a List here:

List<Game> games = new ArrayList<>();
Game g1 = new Game("The Walking Dead", 2012, "Telltale games");
Game g2 = new Game("The Wolf Among Us", 2014, "Telltale games");
Game g3 = new Game("Half-Life 2", 2007, "Valve");
games.add(g1);
games.add(g2);
games.add(g3);

The problem with using an array Game[] is that it can be a hassle to add a new item to the end, due to not knowing where the end is, and also what size is available. Lists avoid these problems.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thank you! Was just trying to see how far I could push a normal array, but I guess it does have its limits. Thank you for your answer! Have a good day – Ty Strong Apr 11 '21 at 13:37