Reputation: 97
I'm working on this program and I keep getting a NullPointerException and I'm not sure why.
//Constructor
public LongTask(SharedResults sharedData,int start, int end)
{
super("Thread");
sharedData=this.sharedData;
start = this.start;
end=this.end;
}
//Run
public void run() {
int sum = 0;
for (int num = start; num<=end;num++)
{
sum+=num;
try {
Thread.sleep((long)(5000*Math.random()));
}
catch (InterruptedException e)
{}
sharedData.addToResult(sum);
}
}
}
I end up getting a NullPointerException error. It looks like my data is not being summed correctly.
Upvotes: 2
Views: 1726
Reputation: 10810
Your problem is:
sharedData=this.sharedData;
start = this.start;
end=this.end;
You are assigned the method level variables to have the values of the class level variables. This needs to be the other way around. The way it's written now, your SharedData will always be null
because it's never getting assigned in the constructor. So later, when you call
sharedData.addToResult(sum);
You are calling attempting to call this method on a null object reference, which explains your NullPointerException
.
Upvotes: 4