Hey folks.
I am one of the many newbs who gets a NullPointerException when trying to make an array of objects.
My complete code is at the end; below are the parts that are related to the exception.
Code://important system variables
int cellX = 10; //dimensions of a cell
int cellY = 10;
int cellsWide = 5; //dimensions of the world
int cellsTall = 5;
//working variables
Cell[][] world = new Cell[cellsWide][cellsTall];
void setup(){
size(cellX*cellsWide,cellY*cellsTall);
background(deadCell);
DrawGrid();
}
void draw(){
for(int i=0;i<cellsWide;i++){
for(int j=0;j<cellsTall;j++){
//display current state
if(world[i][j].state){ //exception occurs here
println("y");
}
}
}
}
I've looked at several other threads- http://processing.org/discourse/yabb2/num_1251480942_seems_similar__but_the_solutions_don.html't seem to work; initializing the world[][] array before setup() doesn't fix it, nor does declaring it outside setup and initializing the object inside. Where is the right place for the line
Code:Cell[][] world = new Cell[cellsWide][cellsTall];
?
Thanks!
Full code below. First, conway2.pde:
Code://important system variables
int cellX = 10; //dimensions of a cell
int cellY = 10;
int cellsWide = 5; //dimensions of the world
int cellsTall = 5;
int generation =3000 ; //time length to display a generation (ms)
//aesthetic values
color deadCell = #CCCCCC;
color liveCell = #FFFFFF;
color gridColor = #000000;
//working variables
Cell[][] world = new Cell[cellsWide][cellsTall]; //dimensions are gridX,gridY
int time;
void setup(){
/* //important system variables
cellX = 10; //dimensions of a cell
cellY = 10;
cellsWide = 5; //dimensions of the world
cellsTall = 5;
generation = 3; //time length to display a generation
//aesthetic values
deadCell = #CCCCCC;
liveCell = #FFFFFF;
gridColor = #FFFFFF;*/
size(cellX*cellsWide,cellY*cellsTall);
background(deadCell);
//world = new Cell[cellsWide][cellsTall]; //initializes all the cells
time=0;
DrawGrid();
}
void DrawGrid(){
stroke(gridColor);
for(int i=1;i<cellsWide;i++){
line(i*cellX,0,i*cellX,height);
}
for(int i=1;i<cellsTall;i++){
line(0,i*cellY,width,i*cellY);
}
}
void draw(){
for(int i=0;i<cellsWide;i++){
for(int j=0;j<cellsTall;j++){
//display current state
if(world[i][j].state){
println("y");
}
}
}
DrawGrid();
}
and then cell.pde:
[code]class Cell{
boolean state; //0 is dead, 1 is alive
int gridX; //X coordinate on the grid
int gridY; //Y coordinate on the grid
boolean nextState;
void showState(int myX, int myY){
if(state){
stroke(liveCell);
}else{
stroke(deadCell);
}
rect(myX*cellsWide,myY*cellsTall,cellX,cellY);
}
Cell(){
if(round(random(0,1)) == 0){
state = false;
}else{
state = true;
}
}
}[/cell]