Processing对象数组初始化异常:仅首个元素赋值其余为null
GalleryRoom数组仅首个元素赋值成功,其余为null且触发空指针异常
尝试用for循环为GalleryRoom对象数组填充实例时,仅首个索引元素被正确赋值,其余元素均为null。循环结束后调用rooms[0].getCount()返回异常数值4111111111116,调用其他元素直接触发空指针异常(NPE)。
原主类代码
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()); } }
原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; } }
问题根源
- 变量名与Processing内置变量冲突:自定义的
frameCount变量与Processing内置全局变量重名,该内置变量用于记录程序运行帧数且会自动递增,导致传入setGallery的count参数被篡改,出现异常返回值。 - 成员变量定义位置错误:
images和imageCount被定义在GalleryRoom类外部,成为全局变量,所有GalleryRoom实例共享这两个变量,后续实例的setGallery调用会覆盖之前的数据,甚至导致实例初始化失败。 - 内部类修饰符冗余:Processing sketch中的内部类无需
public修饰,多余的修饰符可能导致实例化异常。
修正后的代码
主类代码
GalleryRoom[] rooms = new GalleryRoom[12]; // 重命名变量避免与内置frameCount冲突 int imageFrameCount = 10; void setup() { size(800, 600); // 补充Processing必需的窗口初始化 for(int i = 0; i < rooms.length; i++) { rooms[i] = new GalleryRoom(); rooms[i].setGallery("Prefix", imageFrameCount, i); println("Room " + i + " 图片数量:" + rooms[i].getCount()); // 调试打印每个实例的状态 } }
GalleryRoom类代码
class GalleryRoom { // 将成员变量移至类内部,每个实例拥有独立的变量副本 private PImage[] images; private int imageCount; 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"; PImage img = loadImage(filename); if (img == null) { println("图片加载失败:" + filename); // 增加错误提示,排查路径问题 } images[i] = img; } } public int getCount() { return imageCount; } }
额外调试建议
- 确认图片路径正确性:确保
Folder0至Folder11文件夹存在于sketch的data目录下,图片文件名符合Prefix0000.gif、Prefix0001.gif等格式。 - 通过加载失败提示定位问题图片,排查文件缺失或命名错误。
内容的提问来源于stack exchange,提问作者Seer
相关产品推荐
相关产品推荐

