Creating a grid in Java

Soldato
Joined
17 Apr 2003
Posts
6,518
Location
hOme
Hey guys

i'm trying to create a grid of squares in java, not a visual grid but which can be used so that each square can store an individual symbol or character and you can find out the co-ordinates of the symbol at any time

i'm imagining you need to use some sort of array, but all the information i can find on the interweb is only telling me how to draw a grid, when all i really need is a list of co-ordinates for each square in the grid if that makes sense

any ideas? i can get my head around how its logically supposed to be done (you enter the X value for the array, and the Y value) but im stumped as to you actually go to start it :(

cheers guys
 
So what do you want to be able to do with this grid?
Is it going to store Strings, Numbers etc?
What operations do you want to be able to preform on it?

For example:

-Insert an object at X,Y
-Get an object at X,Y
-Insert an object into the first free space
-Get X, Y from an object in the grid (search coords)

I am thinking of a 2D array at the moment but depending on your requirments my approach may change.
 
As RobH says, it sounds like you need a 2D array. It's basically an array of arrays, so you end up with a matrix.

To take an example from a recent assignment:

Code:
        int[][] array2D = {{1, 3, 7, 8,  8,  9,  12},
                         {2, 4, 8, 9,  10, 30, 38},
                         {4, 5, 10,20, 29, 50, 60},
                         {8, 10,11,30, 50, 60, 61},
                         {11,12,40,80, 90, 100,111},
                         {13,15,50,100,110,112,120},
                         {22,27,61,112,119,138,153}};

Would define the array with each set of braces being a row.

The first element would then be

Code:
array2D[0][0]

and the last:

Code:
array2D[array2D.length-1][array2D[array2D.length-1].length-1]

(If it's a square array you can just do array2D[array2D.length-1][array2D.length-1])

array2D[row][column], basically.
 
its basically a grid for a maze game so you need to be able to insert objects (just symbols) at set locations, while other objects need to appear randomly

the program needs to be able to read where any symbol is in the array and print it out to the user too

the program needs to see it as a physical grid like a chessboard although no GUI is needed, i was thinking of a 2D array too with a basic X value and Y value

i know what needs to be and i can see it logically in my head but just cant apply it:(
 
right so each position in the grid would be stored as an integer number, so thats 1681 squares i think (41*41)

i'm trying to get my head around your code, so you'd do each row at a time? How would you be able to figure out the X and Y co-ordinates of a specific position (integer)?
 
The array doesn't have to store integers, it can store anything (like a normal array), however also, like a normal array, it's indexed using integers; one for the column and one for the row.

In the code listed above the entire array is initialized in a single statement, where the entire array is between the outer { } and then each row is defined between another set of { }, with each row and element separated by a comma.

To retrieve an element at a certain point in the array you can either select a row and then column (i.e. index in the row you selected), i.e. in the array above the value 27 would be indexed by: array2D[6][1], i.e. the 2nd element on the 7th row (counting from 0).

To find out where specifically an element is, you'd need a simple search algorithm. The most basic algorithm you can come up with is the following:

Code:
int row, column;
//Iterate over all rows
for(int i = 0; i < array2D.length; i++)
{
   //Iterate over all elements of each row (columns)
   for(int j = 0; j < array2D[i].length; j++)
   {
       //If the element = 27, set the row and columns variables to the position found at
       if(array2D[i][j] == 27)
       {
            row = i;
            column = j;
       }
   }
}
 
this may sound stupid but bear with me:

{1, 3, 7, 8, 8, 9, 12}

the numbers there are just random yeah? so mine would go:

{1,2,3,4,5,6,7,8,9} all the way up to 41, then the next row would start on 42 and so on?

thanks :)
 
Each one of those braces is a row in the array; you can have as many arrays as you like.

Post up how you think you want your array to be and I'll have a look and see if it's right
 
i'm presuming it would be like this:

Code:
        int[][] array2D = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 (all the way up to 41},
                         {42,43,44,45,46,47,48,48 etc etc};

all the way up to 1681 :)
 
Looks ok.

To speed up initializing the array you can do the following:

Code:
public class array {
	public static void main(String args[])
	{
		int[][] array2D = new int[41][41]; //Define and allocate memory for array

		//Start value
		int n = 1;

		//Fill array with values
		for(int i = 0; i < array2D.length; i++)
		{
			for(int j = 0; j < array2D[i].length; j++)
			{
				array2D[i][j] = n;
				n++;	//Increment value for next element
			}
		}

		//Print Array
		System.out.println("Array Contents:");
		for(int i = 0; i < array2D.length; i++)
		{
			System.out.print("[");
			for(int j = 0; j < array2D[i].length; j++)
			{		
				System.out.print(array2D[i][j]);
				if(j < array2D[i].length-1)
					System.out.print(",");
				else
					System.out.print("]\n");
			}
		}
	}
}

The second part will print it to the standard output (useful for debugging)
 
i'm presuming it would be like this:

Code:
        int[][] array2D = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 (all the way up to 41},
                         {42,43,44,45,46,47,48,48 etc etc};

all the way up to 1681 :)

I think you're getting confused here. You don't need to put the row or column numbers in there - you put the symbols at each particular position...

Code:
String[][] array2D {{"hello", "World"},
                          {"Good-bye", "World"}};

In this example array2D[0][0] refers to "hello". array2D[1][1] refers to "World". If you wanted to initialize the entire 2D array in one statement like that yours would be enormous because you would need 41 {...,...,...,...,...}s with 41 elements each.

Its more likely that you will just declare it like this:
Code:
String[][] array2D = new String[41][41];

and then update it when you get a new symbol like this:
Code:
array2D[23][14] = "H";

Hope I haven't confused you more...

EDIT: Maybe I'm getting confused - i read your example as you wanted to use symbols not integers.
 
Last edited:
That's a point; my method above will work if you want those values in the array itself, but follow SoapSurgeon's as to not putting the positions in the array elements, but the values you want. (which may or may not be integers; depends on your implementation of your game)
 
That's a point; my method above will work if you want those values in the array itself, but follow SoapSurgeon's as to not putting the positions in the array elements, but the values you want. (which may or may not be integers; depends on your implementation of your game)

Yeah, im confused as to what he wants now...
 
right guys im getting the hang of this now, one thing though, how do i show the position of a specific symbol in the array? for example i have set the position of the letter P at [20,20] but what code do i need to actually print this out so the user can see where it is?

thanks
 
right guys im getting the hang of this now, one thing though, how do i show the position of a specific symbol in the array? for example i have set the position of the letter P at [20,20] but what code do i need to actually print this out so the user can see where it is?

This method will iterate through the whole array and print positions of the elements specified in the parameter.

Code:
    public void printPosition(String element)
    {
        for(int i = 0; i < array2D.length; i++)
        {
            for(int j = 0; j < array2D[i].length; j++)
            {
                if (array2D[i][j].equals(element))
                {
                    System.out.println("Element \""+element+"\" is located at row: "+(i+1)+" col: "+(j+1));
                }
            }
        }
    }

Making a call to this method such as:

printPosition("P");

Will result in the output:

[B]Element "P" is located at row: 4 col: 4[/B]

If you prefer the column and row counts to start at zero then you can replace the print line with the following:

Code:
System.out.println("Element \""+element+"\" is located at row: "+i+" col: "+j);

This will generate the output as:

[B]Element "P" is located at row: 3 col: 3[/B]

If you happen to have several "P" elements in your array then the output (using the first example) will be like:

Code:
Element "P" is located at row: 2 col: 1
Element "P" is located at row: 4 col: 2
Element "P" is located at row: 4 col: 4

And for the sake of this example, here is the test array:

Code:
        String[][] array2D = new String[][] {   {"A","B","C","D"},
                                                {"P","F","G","H"},
                                                {"I","J","K","L"},
                                                {"M","P","O","P"},
                                                {"Q","R","S","T"}
                                            };
 
right guys im getting the hang of this now, one thing though, how do i show the position of a specific symbol in the array? for example i have set the position of the letter P at [20,20] but what code do i need to actually print this out so the user can see where it is?

thanks

Hmmm, I'm not sure the easiest way but here is one way:

(it uses a custom class 'Location' which is essentially two integers wrapped in a class:

Code:
public class Location
{
private int x,y;

public Location(int x, int y)
{
this.x = x;
this.y = y;
}

public int getX()
{ return this.x; }

public int getY()
{ return this.y; }

}

This is just to allow you to return a Location type from the following method that will search your grid:

Code:
public Location findSymbol(String symbol)
{
   int x = -1;
   int y = -1;

   for(int i = 0; y < 41; y++)  // note, I can't be arsed to work out the code 
   {                                     // for  the length of an array so have used 41
      for(int j = 0; x < 41; x++)
      {
          if(array2D[j][i].equals(symol))
          {
               x = j;
               y = i;
          }
      }
   }
   if(x > -1 && y > -1)
   {
      return new Location(x, y);
   }
   else
   {
      return null;
   }
}

This method returns a Location within the grid that contains the (last) specified symbol. If the symbol isn't in the grid it returns null.

Once youve called that you can get the x and y locations thus:

Code:
Location location = array2D.findSymbol("P");

int x = location.getX();
int y = location.getY();

I'm not saying this is the best way of doing it and I haven't tested it - but the basics are there.

I have no idea why I spent so long typing this up - I must be bored!!

edit: especially since someone else took the time to do something pretty similar!
 
I see RobH got in first and answered the question you were probably asking. Since I've already typed it you may still find it useful :)

Code:
//I've left out quotes round the letters to make it more readable

String[][] array2D = {{a,b,c},
		      {d,e,f},
		      {g,h,i}};

System.out.println(array2D[0][0]);

// outputs a

System.out.println(array2D[1][2]);

//outputs f

or would you want the whole grid printing out?
Code:
System.out.println(java.util.Arrays.deepToString(array2D));
outputs:
[[a, b, c], [d, e, f], [g, h, i]]

but you probably want it formatted more like
a b c
d e f
g h i

for that look at the code Phill99 posted it will output:
Array Contents:
[a,b,c]
[d,e,f]
[g,h,i]
 
Here is my original method modified to use SoapSurgeons Location class if you want the value returned (so you can use it for futher processing) rather than printed. The modified method will only return the first occurence of the element you're searching for, you could return an array or collection of Locations if required.

Code:
    public Location getPosition(String element)
    {
        for(int i = 0; i < array2D.length; i++)
        {
            for(int j = 0; j < array2D[i].length; j++)
            {
                if (array2D[i][j].equals(element))
                {
                    return new Location(i,j);
                }
            }
        }
    }

It's good to see other peoples approaches to this problem, don't hesitate to post even if someone else has already answered.
 
Last edited:
i was using one java file and each class as a public void called by public static void main(String[]args) at the beginning of the program, i've got a feeling i should be using seperate java files for classes...:(
 
i was using one java file and each class as a public void called by public static void main(String[]args) at the beginning of the program, i've got a feeling i should be using seperate java files for classes...:(

Hard to understand what you mean there because classes don't have return types.

Usually you would have 1 class in it's own file (there are, as always, exceptions to this rule). Without trying to patronise, I think you have 1 class with several methods in? Which is certainly one way of doing things but you lose all the benefits of OO design then.

I would have a separate class for Location and one for Grid (probably one to launch the program too), but without knowing the full context of the problem it is hard to say.
 
Back
Top Bottom