My Own Alarm Clock

edited March 2017 in Questions about Code

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()
    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()

void draw()
  for (int i=0; i < clocks.length; i++)

Thanks a lot for your help!



  • Edit post, highlight code, press ctrl-o to format.

    Which line is showing the error?

  • Answer ✓

    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

    clock = new Clock();
  • 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.

  • edited March 2017

    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

  • is it not enough to have new Clock defined as a global variable already?

    line 28? that's not defining the clock, that's defining an ARRAY of clocks. you need to then instantiate the individual clocks.

    Clock cannot be resolved to be a variable

    sorry, slight mistake in what i posted. it needed to be

    clocks[0] = new Clock();

    but it sounds like you've fixed that already.

    might be an idea to post your current code...

Sign In or Register to comment.