简体   繁体   中英

null pointer exception Java with drawing 2D array list

This might be a dumb question, but why am I getting a null pointer exception here? I am trying to paint a tile map for a java applet. I just pasted the problem areas.

private int[][] map;     
public void init()
{
   int map[][]={ {0,0,0},
                {1,1,0},
                {0,0,0} };

}
public void drawCaveTiles(Graphics g)
{
   for(int i = 0; i <= 3; i++)
   {
       for( int j = 0; j <= 3; j++)
       {
           if(map[i][j] == 1)
           {
               g.drawImage(snow_brick, i*64, j*64, this);
           }
           if(map[i][j] == 0)
           {
               g.drawImage(black, i*64, j*64, this);
           }  
       }
    }

}

I fixed it

map =new int[][] { {0,0,0},
          {1,1,0},
          {0,0,0} };
  int map[][]={ {0,0,0},
                {1,1,0},
                {0,0,0} };

Here in the method init() , you are creating a new map which is local to the method init() and not initializing instance member map .

Change it to

   map ={ {0,0,0},
                {1,1,0},
                {0,0,0} };

And make sure you calling inti() method before calling drawCaveTiles() method.

or Since it is a static data. Move that line to declaring place.

In your init() method, you are hiding the class field map , because you are declaring it again (in the local block of the method init() ).

Also, make sure you are calling the init() method. It should be called in your constructor:

public class YourApplet {
    public YourAppler() {
        init();
    }

    public void init()
    {
       map[][]={ {0,0,0},
                 {1,1,0},
                 {0,0,0} };
    }
}

The local variable int map[][] in the init() is shadowing your instance variable private int[][] map; . Do not create a new local int map in the init() method. Just use the global map array in the init() method.

public void init() {
    map={ {0,0,0}, {1,1,0}, {0,0,0} };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM