Where are you getting a NullPointerException
?
Processing 4.3.4 will show you where. (Newer versions of Processing may not show this.)
Adding this to your code example shows that the array is increasing and the logic for the small snippet shared with us seems correct:
void keyPressed()
{
setType();
}
Some minimal code from my personal exploration of this topic to update ants in each cell:
Code < Click here to expand!
// Code pieced together from various elements in this topic:
// https://discourse.processing.org/t/trouble-expanding-and-writing-to-array-of-objects/46750
// Some editions were made by glv in the exploration of this.
// A keypress (0 or 1) will increase the number of ants in each cell.
// This can be expanded to fill any number of cells.
int antsPerNest = 1; // Initial
// int antAmt = 0; // No longer be global, but per cell
int cellRows = 2;
int cellCols = 2;
int cellAmt = cellRows * cellCols;
int cellSize = 200;
cell[] c;
void setup() {
c = new cell[cellAmt];
println(c.length);
// generate cells
int i = 0;
for (int y = 0; y < cellRows; y++) {
for (int x = 0; x < cellCols; x++) {
c[i] = new cell((x * cellSize) + (cellSize / 2),
(y * cellSize) + (cellSize / 2));
// println(c[i].cellXY.x, c[i].cellXY.y);
i++;
}
}
println(i);
}
void draw() {
// No drawing yet
}
class cell {
PVector cellXY;
ant[] antsInCell; // Array to hold ants for this specific cell
int currentAnts = 0; // Counter for ants in this cell
cell(float x, float y) {
cellXY = new PVector(x, y);
antsInCell = new ant[0]; // Initialize with an empty array
}
// setType() function moved into the cell class
void setType() {
antsInCell = (ant[]) expand(antsInCell, currentAnts + antsPerNest);
// For examining output:
println("Expanded:");
debug(antsInCell);
for (int j = currentAnts; j < antsInCell.length; j++) {
// Spawn ants randomly within the cell's boundaries
antsInCell[j] = new ant(
random(cellXY.x - cellSize / 2, cellXY.x + cellSize / 2),
random(cellXY.y - cellSize / 2, cellXY.y + cellSize / 2)
);
println("Added:", j, antsInCell[j].antXY.x, antsInCell[j].antXY.y);
}
currentAnts += antsPerNest;
// For examining output:
println("Updated:");
debug(antsInCell);
}
}
class ant {
PVector antXY;
ant(float x, float y) {
antXY = new PVector(x, y);
}
}
void keyPressed()
{
if (key == '0') {
println("Cell 0:");
c[0].setType(); // Call setType on the first cell
}
else if (key == '1') {
println("Cell 1:");
c[1].setType(); // Call setType on the second cell
}
// Extend as needed...
}
// Debug and examining objects for nulls
void debug(ant[] arr) {
for (int n = 0; n < arr.length; n++) {
if (arr[n] == null) { //object
println("null");
} else {
println(n, arr[n].antXY.x, arr[n].antXY.y); //element
}
}
println();
}
The full code (not shared) displayed ants per cell and updated with keyPressed()
:
Sharing with the community!
I also had errors and NullPointerException
along the way and sorted these out with some troubleshooting and experience.
There may be something in there of interest.
:)