处理未初始化的对象数组

问题描述 投票:0回答:1

我只是尝试使用 for 循环用对象填充对象数组,但由于某种原因它只填充第一个索引,数组的所有其他索引保持为空。我试过引用 other Processing code 做同样的事情,据我所知我的代码匹配吗?也许这只是我遗漏的一个小错误,但它已经逃避了我一个小时 x-x

这是我的主课:

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());
  }
}

在遍历整个 for 循环后,打印 rooms 数组对象 0 的 getCount 方法给出

4111111111116
,打印任何其他对象给出 NPE。

还有我的 GalleryRoom 对象类:

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;
  }
}
arrays object processing
1个回答
0
投票

我想我在您的代码中发现了问题。看起来变量 images 和 imageCount 是全局定义的,这导致了一些奇怪的行为。相反,您应该将它们作为实例变量放入 GalleryRoom 类中。修复方法如下:

public class GalleryRoom {
  PImage[] images;
  int imageCount;

  public void setGallery(String imagePrefix, int count, int x) {
    // ... rest of the code
  }

  public int getCount() {
    return imageCount;
  }
}

现在,rooms 数组中的每个对象都将拥有这些变量的独立副本,这应该可以解决您的问题。此外,您可能希望将 print 语句移到 setup() 方法的循环之外,因此它只打印一次:

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

试一试,让我知道它是否适合你!祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.