We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi guys, I am trying to create my own alarm clock, so far I only have a class Clock which is supposed to show the time, havent even gone to the alarm clock etc yet, but it already shows me a nullPointer Exception and I am not sure why..
class Clock
{
int hh = 0;
int mm = 0;
int ss = 0;
Clock ()
{
hh = hour();
mm = minute();
ss = second();
}
void display()
{
fill(128);
rect(50,50,300,150);
fill(255,255,255);
textSize(36);
textAlign(CENTER, CENTER);
String hh = nf(hour(),2);
String mm = nf(minute(),2);
String ss = nf(second(),2);
text(hh + ": " + mm + ": " + ss, 60, 60);
}
}
Clock[] clocks = new Clock[1];
void setup()
{
size(400,400);
}
void draw()
{
background(0,180,100);
for (int i=0; i < clocks.length; i++)
{
clocks[i].display();
}
}
Thanks a lot for your help!
Answers
Edit post, highlight code, press ctrl-o to format.
Which line is showing the error?
You don't initialise the clock. You initialise the array of clocks, but not the clocks themselves.
And nothing in your constructor is ever used - everything is overridden in display ().
Thanks for the answer and sorry for the bad formatting. I am still very new to this and also not entirely sure how to initialise the clock itself. What should I put in the constructor in your opinion?
Well, tbh, nothing. Certainly not the current time, because, even 1 second later, that's inaccurate. For an alarm clock you'd probably need to store the time of the alarm. But how would you get that info?
Anyway, to fix the npe, add line 32
Also, be aware that draw () runs 60 times a second. Your clock updates once a second. So 90 percent of the time it's just a waste. I'd turn the frame rate down to, say 5.
is it not enough to have new Clock defined as a global variable already? also, now it that i added line 32 and removed the content of the constructor, it doesnt show the nullpointer exception anymore but Clock cannot be resolved to be a variable. Noted, the comment with the frame rate. gona fix that later. EDIT: works now, had to put something in the constructor it kept telling me, so I just put the x/y coordinates and now its working. Thank you for your help
line 28? that's not defining the clock, that's defining an ARRAY of clocks. you need to then instantiate the individual clocks.
sorry, slight mistake in what i posted. it needed to be
but it sounds like you've fixed that already.
might be an idea to post your current code...