Drawing a grid error

I'm trying to draw a grid using a 2D array of coordinates. I get an error on line 34. "ArrayIndexOutOfBoundsException:0" I know there is something fundamentally wrong with the logic here but I don't have the knowledge yet!

I know I could draw a grid a different way but now I'm a bit stubborn with this method and would like to know why this isn't working at the moment. Thanks

void setup() {

  size(1000,1000);
  grid Grid;
  Grid = new grid (10, 10 , 100, color(100)); 
  Grid.load();
  Grid.display();
}

// A grid object
class grid {

    int cols;
    int rows;
    int s; 
    color c;
    int [][] coordinates = new int [cols][rows];

  // Constructor 
    grid (int _cols, int _rows, int _s, color _c) {
    cols = _cols;
    rows = _rows;
    s = _s;
    c = _c;
   }

    // Initialises the 2D array "coordinates" with x and y 
    // coordinates derrived from the amount of cols 
    // rows stated    

    void load(){
    for (int i = 0; i < cols; i++) {
      for (int j = 0; j < rows; j++) {
        coordinates [i][j] = i*s;
        }
      }
    }

    // Draws rectangles with x,y values from 2D array "coordinates".
    // The values are obtained by looping through the array.
    void display() {
      for (int i = 0; i < cols; i++) {        
        for (int j = 0; j < rows; j++) {
          fill(c);
          rect(coordinates[i][0], coordinates[0][j], s, s);
        }
      }    
    }
}
Tagged:

Answers

  • Answer ✓
    // A grid object
    class grid {
    
        int cols;
        int rows;
        int s; 
        color c;
        int [][] coordinates; // At this points rows and cols = 0
    
      // Constructor 
        grid (int _cols, int _rows, int _s, color _c) {
        cols = _cols;
        rows = _rows;
        // Now we can create the array
        coordinates = new int [cols][rows];
        s = _s;
        c = _c;
       }
    
  • @quark Thank you so much! Glad to know it was just a simple mistake- I will make sure to check declaration orders next time. D

Sign In or Register to comment.