Search code examples
arraysmethodsruntime-erroris-empty

Exception in thread "main" java.lang.NullPointerException? What does this mean?


I have an error when trying to run this program. This is not the entire program just the few details I think where the problem is. The error points out

if(board[randSpace].isEmpty())  and 
cl.makeChutes(5);"

Error is :

"Exception in thread "main" java.lang.NullPointerException
at ChutesAndLadders.makeChutes(ChutesAndLadders.java:29)
at ChutesAndLadders.main(ChutesAndLadders.java:67)"

This is my program:

import java.util.Random;
public class ChutesAndLadders{

Cell [] board = new Cell [100];
Random rand = new Random ();
public int chutes, ladders;

public void makeChutes (int a ){
    int makeChutes = a;
    for (int i = 0; i < a; i++){
        int randSpace = rand.nextInt(99);
        if(board[randSpace].isEmpty())
            board[randSpace] = new Cell (-10,"C");
        else 
            i--;
    }
}

 public static void main(String[] args) {
 // Create an instance of ChutesAndLadders
 ChutesAndLadders cl = new ChutesAndLadders(10,10);

 // Randomly place 5 more chutes and 5 more ladders
 cl.makeChutes(5);
 cl.makeLadders(5);

Here is my isEmpty: public boolean isEmpty(){ for(int i = 0; i < board.length; i++) { if (board[i].isEmpty()) return true; } return false; }

I could be entirely wrong on my coding. I'm still learning so please be patient. Thank you!


Solution

  • Following on what Dewfy said, board is an array of Cell objects. That means it is a placeholder for Cell objects --a bunch of nulls waiting to be replaced by a Cell.

    If say, the object at position 1 (board[1]) has not been assigned a Cell object (i.e. you haven't issued a command like board[1]=new Cell() or something like that) then board[1] is null. Therefore if you were to ask board[1].isEmpty() you would get a NullPointerException because you are trying to call a method on a null object.

    Now, your error is likely to come from board[randSpace] being null. So, the question is: does it contain a Cell object? Have you initialized your array with Cell objects?

    One way to check this would be to say: if (board[randSpace]==null || board[randSpace].isEmpty()) .....