开发者

Processing - Simple Null Pointer Error

I have created an array of custom objects in my processing code and then proceed to init it. However, for some reason I run into a null pointer exception at: objectArray[i].siteID = 5;

I have spent the last 2 hours trying to 开发者_C百科find info on how to fix this but the syntax seems to be correct!

Code:

class TtalkObject{
  int siteID = 0;
  String URL = "test";
  int commentNum = 5;
  int averageLength = 5;

}

PFont f;
TtalkObject[] objectArray;
int whatObjectPart = 0;
int whatObject = 0;

void setup()
{
    size(300,300);
    f=createFont("Arial",16,true);
    objectArray = new TtalkObject[50];

    for (int i = 0; i < 50; i ++){
        objectArray[i].siteID = 5;
        objectArray[i].URL = "test";
        objectArray[i].commentNum = 10;
        objectArray[i].averageLength = 10; 
    }

}


objectArray = new TtalkObject[50]; //you have initilized array of 50 reference

but it doesn't mean each 50 reference points to an object

you need to create object for each of them.

Make it

objectArray = new TtalkObject[50]; 
for (int i = 0; i < 50; i ++){
 objectArray[i] = new TtalkObject();// or some other preferred initialization
 objectArray[i].siteID = 5;


Looks like you're never creating an instance of your TtalkObject, you're just initializing an array to hold fifty of those objects.

I'm not familiar with java syntax, in c# it'd be

for (int i = 0; i < 50; i ++){
 objectArray[i] = new TtalkObject();
 objectArray[i].siteID = 5;
 objectArray[i].URL = "test";
 objectArray[i].commentNum = 10;
 objectArray[i].averageLength = 10;
}


Null pointer error usually occurs when you use something that you have not allocated memory for or when you access some variable which is out of scope.


Put following on line 22

objectArray[i] = new TtalkObject();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜