We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there
I'm new to processing and I really can't figure out why in the code below I get a NullPointerException with the array InWorld[] creatures when it contains more than 2 or 3 objects. It sometimes work with 20, but then Processing won't open the sketch a second time, and i get a NullPointerException. As you can notice, I declared and initialized OutWorld[] souls in the exact same way and it works, even when it contains 2000 objects. // Working with Processing 2.1.1 for Windows 64bits.
Specific parts :
InWorld[] creatures;
OutWorld[] souls;
void setup(){
/*......*/
creatures = new InWorld[2];
for(int c=0; c<creatures.length; c++){
/*......*/ creatures[c] = new InWorld(id,shade,lifeTime,energy);
}
souls = new OutWorld[2000];
for(int s=0; s<souls.length; s++){
/*......*/souls[s] = new OutWorld(random(-120,360), random(10,80));
}
}
void draw(){
force.display();
for(int c = 0; c < creatures.length; c++){
creatures[c].update();
creatures[c].display();
}
for(int s = 0; s < souls.length; s++){
souls[s].update();
souls[s].display();
}
}
Totality of the main sketch :
Force force;
InWorld[] creatures;
OutWorld[] souls;
void setup(){
size(480,640);
force = new Force();
creatures = new InWorld[2];
for(int c=0; c<creatures.length; c++){
int id;
int shade;
int lifeTime;
float energy;
float probability = random(1);
if(probability > 0.1 && probability < 0.50){
id = 255;
shade = int(random(192,255));
lifeTime = shade;
energy = random(63.5,127);
creatures[c] = new InWorld(id,shade,lifeTime,energy);
} else if(probability > 0.50 && probability < 1){
id = 0;
shade = int(random(1,64));
lifeTime = shade;
energy = random(63.5,127);
creatures[c] = new InWorld(id,shade,lifeTime,energy);
}
}
souls = new OutWorld[2000];
for(int s=0; s<souls.length; s++){
float probability = random(1);
if(probability >= 0 && probability <= 0.25){
souls[s] = new OutWorld(random(-120,360), random(10,80));
} else if(probability >= 0.25 && probability <= 0.50) {
souls[s] = new OutWorld(random(-120,-11), random(-480,0));
} else if(probability >= 0.50 && probability <= 0.75) {
souls[s] = new OutWorld(random(-120,360), random(-560,-491));
} else if(probability >= 0.75 && probability <= 1) {
souls[s] = new OutWorld(random(250,360), random(-480,0));
}
}
}
void draw(){
background(255,235,180);
force.display();
for(int c = 0; c < creatures.length; c++){
creatures[c].update();
creatures[c].display();
}
for(int s = 0; s < souls.length; s++){
souls[s].update();
souls[s].display();
}
}
Answers
The problem is in the creation of the creatures themselves.
In lines 19 - 32 a creature is NOT created if the probability <= 0.1 it means that some of the array elements are null.
thank you so much ! seems perfectly logical, but i wouldn't have found.