2D Arrays, declaring globally?

I’m trying to make a single 2D array called “map” and have it store the data for the current level. However, when I try to make the 2D array at the beginning of the class like so -

int[][] map;

it then gives me an error when I do this later on -

if (level == 1)
		{
			map = {
				{2, 2, 2, 2, 2, 2, 2, 2, 2,}, //
				{2, 2, 2, 1, 3, 3, 2, 2, 2,}, //
				{2, 2, 2, 2, 2, 2, 2, 2, 2,}, //
				{2, 2, 1, 3, 0, 3, 2, 2, 2,}, //
				{2, 2, 1, 2, 3, 2, 2, 2, 2,}, //
				{2, 2, 2, 2, 1, 1, 2, 2, 2,}, //
				{2, 2, 2, 2, 2, 2, 2, 2, 2,} //
			};
		}

The error is “Array constants can only be used in initializers”. I tried the almighty google, and learned nothing.

The reason I want to do this is because I used to have it like this -

if (level == 1)
		{
			int[][] map = {
				{2, 2, 2, 2, 2, 2, 2, 2, 2,}, //
				{2, 2, 2, 1, 3, 3, 2, 2, 2,}, //
				{2, 2, 2, 2, 2, 2, 2, 2, 2,}, //
				{2, 2, 1, 3, 0, 3, 2, 2, 2,}, //
				{2, 2, 1, 2, 3, 2, 2, 2, 2,}, //
				{2, 2, 2, 2, 1, 1, 2, 2, 2,}, //
				{2, 2, 2, 2, 2, 2, 2, 2, 2,} //
			};
		}

But that is a local variable, and I can’t use it later when it’s needed here -

for (int x = 0; x < 9; x++)
			{
				for (int y = 0; y < 7; y++)
				{
					System.out.println(x + " x, " + y + " y");
					
					playerData = map[py][px];
					mapData = map[y][x];
				
					if (mapData == 0)
					{
						px = x;
						py = y;
					}
                                        etc... spawn boulders etc

Does anyone have any idea how I can do this without an error occurring?

The whole reason I want this is to have multiple levels, but only have one array it has to check. It can can see what the level is and set the array accordingly.

Here’s my source - http://www.mediafire.com/?34c0uw48ap3pafk

Thanks,
-Nathan

You can only do it that way immediately when declaring it. Your way, you need to add “new int[][]”:


map = new int[][] {
   { ..... },
   { ..... },
   .....
};

Oh :’(

So there’s no way for me to use one 2D array for all of the different levels since I can’t access the array from outside of that method?

Of course you can access the array from outside the method. What I meant was to use that initialization method with the curly braces, all you need to add is “new int[][]”, that’s all. :stuck_out_tongue:

crazier way, add one more dimension representing level ;D