Minor Problem with arrays and loops

PVector[] record = new PVector[100];
int curr = 0;

void setup() {
  size(800, 800);
  for (int i = 0; i<record.length; i++) {          
    record[i]= new PVector(100, 100);
  }
}

void draw() {
}

void mousePressed() {
  record[curr].x = mouseX;
  record[curr].y = mouseY;
  curr++;
  print (curr);

  if (curr==1) {
    for (int  i=1; i<record.length; i++) {
      record[i] = record[0];
      print("ladida");                         //debug
    }
    print("ladida");                           //debug
  }
  print (record[0]);
  print (record[1]);
  print (record[2]);
  print (record[3]);
  print (record[4]);
  print (record[curr]);
  println ();
}

What the code is suppose to do.

First Click should store Mouse X and Y value in record[0] and then make all the other values of record(eg1,2,3,4,5,6…) equal to record[0]. So, at this point all the values in record should be the same. From the second click, only the values of the next record gets updated. So, the second click should update record[1] and the third should update record[2] and the forth record[3] and so on.

What it does.

First Click stores Mouse X and Y value in record[0] and then makes all the other values of record(eg1,2,3,4,5,6…) equal to record[0]. The second click also does the same, it again copies the value onto all the array instead of only 1 box.

1 Like

replace int i=1 by a variable start_i (because then make all the other values of record(eg1,2,3,4,5,6…) equal to…)

1 Like

I dont understand, can u please clearify

Here is an example with only four PVectors.

Click 1 loops 0,1,2,3
Click 2 loops 1,2,3
Click 3 loops 2,3
Click 4 loops 3

Change the size of record to change the number of clicks and their results.

PVector[] record = new PVector[4];
int curr = 0;

void setup() {
  size(800, 800);
  for (int i = 0; i<record.length; i++) {          
    record[i]= new PVector(100, 100);
  }
}

void draw() {
}

void mouseReleased() {
  for (int  i=curr; i<record.length; i++) {
    record[i].x = mouseX;
    record[i].y = mouseY;
  }
  curr = (curr+1)%record.length; // wraps around after n clicks
  println(record);
}

This mechanism is suspicious, though – I wonder whether you are duplicating data as a workaround for an array display problem that might have a different, better solution. For example, when you display your data in draw, you could only display up to curr, and ignore future (empty) points rather than filling them with redundant data. Or you could use an ArrayList, and add points dynamically as you need them.