Array reset help

I’m trying to have the array reset all of the numbers to random numbers when I press the ‘r’ key but it’s not working

int many=20;
int[] array = new int[many];

void setup() {
  size(640, 480);
}
void draw() {
  scene();
  // controls();
  // showAll();
  reset(array, many);
  show(array, many);
  noLoop();
}

void reset(int[] a, int m) {
  for (int i=0; i<m; i++) {
    a[i] = int(random(0, 1000));
  }
}
void show(int[] a, int m) {
  for (int i=0; i<m; i++) {
    textSize(16);
    text(a[i], 75, 70+i*15);
  }
}
void scene() {
  background(195, 103, 207);
  textSize(24);
  // text( title, 275, 25);
  textSize(18);
  text( " Numbers ", 45, 45);
  // text( " Controls ", 225, 45);
}
void keyPressed() { 
  if (key == 'q') exit(); 
  if (key == 'r') reset(array, many);
}
1 Like

That noLoop() at the end of draw is screwing you over. You are resetting the array succesfully, but because of noLoop(), the sketch is not redrawn.

This means you reset() the array in draw, show it and then stop drawing forever. So even if you change the values of array, they won’t be shown on-screen.

To fix this, move reset(array) into setup and remove the noLoop() from draw.

Also, you don’t need the variable many to keep track of the amount of elements, because every array has an inbuilt length variable that tells you exactly that and can be accessed like this: array.length.

2 Likes

Thanks for the help and the tip!

I didn’t realize that noLoop() meant to stop drawing forever.

1 Like
1 Like