public void display(Date date) {
boolean loop = true;
System.out.println("Events on " + date.toString());
for (int i = 0; i < schedule.length; i++) {
while (loop) {
Date tmp = schedule[i].nextOccurrence();
if (tmp.compareTo(date) == 0) {
System.out.println(schedule[i].nextOccurrence().toString());
}
}
schedule[i].init();
}
}
The above is supposed to print out an occurrence of an event if it falls on the date given to the method. The method nextOccurrence grabs the next occurrence of an event (if its weekly or daily). nextOccurence looks like this for a DailyEvent:
public Date nextOccurrence() {
if (timesCalled == recurrences) {
return null;
}
else {
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
cal.add(Calendar.DATE, timesCalled);
timesCalled++;
return cal.getTime();
}
}
I call schedule[i].init() to reset the number of times called to 0 (daily events have a limit of number of times they can be called, denoted as an int with the variable recurrences).
Basically, my problem is that I'm getting a NullPointerException for this line:
if (tmp.comp开发者_开发知识库areTo(date) == 0) {
I've tried everything and I'm completely lost. Any help would be great!
your method nextOccurence
may return null
, you need to check for that :
if (tmp != null && tmp.compareTo(date) == 0) {
Also, your loop
variable is never set to false
and will cause an infinite loop... And you call nextOccurrence()
twice within your loop; is that desired?
You might consider redesigning your getNextOccurence()
and have your schedule
class implement an iterator for your dates. This will change your loop with
Iterator<Date> iterator = schedule[i].occurenceIterator();
Date tmp;
while (iterator.hasNext()) {
tmp = iterator.next();
if (tmp.compareTo(date) == 0) {
System.out.println(tmp.toString());
}
}
which is cleaner than what you're using.
I have a feeling that your nextOccurrence()
function is returning null. If it returns null, then you'll get a NullPointerException
when you try to use the compareTo
function on that object.
Why didn't you step through this in a debugger?
My guess is that
public Date nextOccurrence() {
if (timesCalled == recurrences) {
return null; // <<<<
}
the line with '<<<<' is the root of the problem.
精彩评论