Search code examples
javaarrayscoordinatesnested-loops

Java - Array of Coordinates


I need to write an single array of coordinates. I have written the Coordinate class such that:

public class Coordinate {
   int row;
   int column;

   public Coordinate (int column, int row) {
   ...
   }
}

In my main method, I want to have an array Coordinate positions[] = new Coordinate[64] and populate it with values (0,0), (0,1), ..., (7,6), (7,7).

Any idea on how to approach this? I have tried nested loops but I can't get it right.

EDIT: sorry guys, still trying to figure things out with Stack Overflow I am doing:

  for(int i=0; i<64; i++) {
        for(int c=0; c<8; c++) {
            for(int r=0; r<8; r++) {
            positions[i] = new Coordinate(c, r);
            }
        }
      }

But its making a mess and looping way too much


Solution

  • you are looping too much because of your first loop , a simple solution would go like this :

    int i=0;
     for(int c=0; c<8; c++) {
            for(int r=0; r<8; r++) {
            positions[i] = new Coordinate(c, r);
            i++; 
            }
        }