-1

I'm just trying to fill an Object array with Objects using a for loop but for some reason it only fills the first index, all other indices of the array remain null. I've tried referencing other Processing code which does the same thing, and as far as I can tell my code matches? Maybe it's just a small error I'm missing but it has evaded me for like an hour x-x

Here's my Main class:

GalleryRoom[] rooms = new GalleryRoom[12];
int frameCount = 10;

void setup() {
   for(int i = 0; i<rooms.length;i++) {
   rooms[i] = new GalleryRoom();
   rooms[i].setGallery("Prefix", frameCount, i);
   print(rooms[0].getCount());
  }
}

Printing the getCount method for object 0 of rooms array gives 4111111111116 after iterating through the entire for loop, printing any other object gives NPE.

And my GalleryRoom Object class:

PImage[] images;
int imageCount;

public class GalleryRoom {
  public void setGallery(String imagePrefix, int count, int x) {
    imageCount = count;
    images = new PImage[imageCount];
    for (int i = 0; i < imageCount; i++) {
      String filename = "Folder"+x+"/"+imagePrefix + nf(i, 4) + ".gif";
      images[i] = loadImage(filename);
    } 
  }
  public int getCount() {
    return imageCount;
  }
}
2
  • Language tag? Is this Java or C#? (Your referenced question refers to Java.) Commented Apr 24, 2023 at 3:36
  • 1
    Processing is a java based language: processing.org Commented Apr 24, 2023 at 4:39

1 Answer 1

0

I really urge You to define the state of the Object inside the body of the Class:

public class GalleryRoom {
  PImage[] images;
  int imageCount;
  
  GalleryRoom(String imagePrefix, int count, int x) {
    this.imageCount = count;
    this.images = new PImage[imageCount];
    for (int i = 0; i < imageCount; i++) {
      String filename = "Folder"+x+"/"+imagePrefix + nf(i, 4) + ".gif";
      //images[i] = loadImage(filename);
      println(filename);
    }
  }
  public int getCount() {
    return this.imageCount;
  }
}

Now, You can call new GalleryRoom:

GalleryRoom[] rooms = new GalleryRoom[12];
int frameCount = 10;

void setup() {
  for (int i = 0; i<rooms.length; i++) {
    rooms[i] = new GalleryRoom("Prefix", frameCount, i);
    println(rooms[0].getCount());
  }
}

Just a friendly reminder that It's a convention to use a constructor with parameters instead of a method that configures the created object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.