1

I excepted that my functions in Level.java class allow me to make 2D array copy at any time in my program then change size of level array and fill it with values of copy and at last display it.

When I try to run my program it shows NullPointerException at line 24 in Level.java (a part which replaces the values).

Game.java Class

package main;

public class Game {

public static void main(String[] args) {
    Level lvl = new Level();
        char[][] exampleLevelTemplate = new char[][] {
            {'#','#','#'},
            {'#','#','#'},
            {'#','#','#'}
        };
        lvl.setLevelSize(3,3);
        lvl.setLevelLayout(exampleLevelTemplate);
        lvl.displayLevel();     
    }

}

Level.java Class

package main;

public class Level {

private int levelWidth;
private int levelHight;
private char[][]level;

public void setLevelSize(int Width,int Height)
{
    levelWidth = Width;
    levelHight = Height;
    char[][]level = new char[levelWidth][levelHight];
}

public void setLevelLayout(char[][]levelTemplate)
{
    int a; 
    int b;
    for(a=0; a < levelWidth; a++)
    {
        for(b=0; b<levelHight; b++)
        {
            level[a][b] = levelTemplate[a][b]; //Error happens here
        }
    }       
}

public void displayLevel()
{
    int a; 
    int b;
    for(a=0; a < levelWidth; a++)
    {
        for(b=0; b<levelHight; b++)
        {
            System.out.println(level[a][b]);
        }
    }
}

}

1 Answer 1

1

Change your setLevelSize method to this:

public void setLevelSize(int Width,int Height)
{
    levelWidth = Width;
    levelHight = Height;
    level = new char[levelWidth][levelHight];
}

You will see that line:

char[][]level = new char[levelWidth][levelHight];

was changed to:

level = new char[levelWidth][levelHight];

You need to just assign the array Object to array reference variable "level" and not create a local one and initialize it like you did.

You have been assigning value to a null array reference variable and therefore got NullPointerException.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.