NullPointerException
in
Programming Questions
•
1 month ago
I'm still a beginner in coding and decided to practice basic algorithms and how to make objects display at a given time after pressing play. My question is why does the following code yield the error message "NullPointerException"? The bold blue line is the one that is highlighted with the error message. Basically, I was trying to create a sketch that would create a button at a random location every 2 seconds. What am I overlooking? Thanks in advance for all the help.
Button[] buttons;
Timer timer;
int totalButtons = 0;
void setup() {
size(800, 800);
smooth();
buttons = new Button[100];
timer = new Timer(2000);
timer.start();
}
void draw() {
background(255);
buttons = new Button[100];
if (timer.isFinished()) {
buttons[totalButtons] = new Button();
totalButtons++;
if (totalButtons >= buttons.length) {
totalButtons = 0;
}
timer.start();
}
for (int i = 0; i < totalButtons; i++) {
buttons[i].display();
}
}
class Timer {
int savedTime;
int totalTime;
Timer(int totalTime_) {
totalTime = totalTime_;
}
void start() {
savedTime = millis();
}
boolean isFinished() {
int passedTime = millis() - savedTime;
if (passedTime > totalTime) {
return true;
}
else {
return false;
}
}
}
class Button {
color c;
float xpos;
float ypos;
float r;
Button() {
c = color(0, 0, 200);
xpos = random(width);
ypos = random(height);
r = 8;
}
void display() {
fill(c);
ellipse(xpos, ypos, r*2, r*2);
}
}
1