0

I'm writing a program using JGrasp, where tile is a class. The Following code compiles:

        tile ext = new tile();
        ext.assignValues(0);
        g.setColor(ext.color);
        g.fillRect(10+20, 35+20, 20, 20);

But the following does not:

        tile[][] ext = new tile[1][1];
        ext[0][0].assignValues(0);
        g.setColor(ext[0][0].color);
        g.fillRect(10+20, 35+20, 20, 20);

Am I initializing the 2D array wrong, or am I misunderstanding how arrays work.

2 Answers 2

4

ext[0][0] not initialized as tile[][] ext = new tile[1][1]; is Array of instances of tile (Object In general term) but you have to initialize every object stored at array index before using those objects as default value is null for every element here.

tile ext[0][0]= new tile(); //Have to initialize it first 
//And than use it in your code

As I think you won't get anny issue during compilation but it will throw NullPointerException while you execute your code which is trying to manipulate null value.

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

Comments

3

You have initialized the array ext[][], but you have not initialized the tile in position [0][0]. Therefore it is empty, and trying to call a method would be like accessing a method of a null value.

tile[][] ext = new tile[1][1];
ext[0][0] = new tile();
ext[0][0].assignValues(0);
g.setColor(ext[0][0].color);
g.fillRect(10+20, 35+20, 20, 20);

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.