Reputation: 11
The problem I have has had me tearing my hair out for days now. As you can see I put printlns there so I can check where the error occours. After looking at the data in my table the nullpointer exception occours after the last data piece. Why does my code not stop it from looping another time?
public void prepare(int sheet, Students [] gradeSpecific, Students [] mcl)
{
String [] useableCandidates;
useableCandidates = new String [200];//school never has more than 40 candidates therefore 200 is more than enough
int i= 0;
if(sheet==1)
{
while(!gradeSpecific[i].getFirst_name().equals(null) && !gradeSpecific[i].getSurname().equals(null))
{
if(useableCandidates[i]==null)
{useableCandidates[i]= new String();}
System.out.println(gradeSpecific[i].getFirst_name()+gradeSpecific[i].getSurname());
useableCandidates[i]= gradeSpecific[i].getFirst_name()+" , "+gradeSpecific[i].getSurname();
System.out.println(useableCandidates[i]);
i++;
}
}
else
{
while(!mcl[i].getFirst_name().equals(null) || !mcl[i].getSurname().equals(null))
{
useableCandidates[i]= mcl[i].getFirst_name()+" , "+mcl[i].getSurname();
i++;
}
}
}
Upvotes: 1
Views: 88
Reputation: 1678
First of all, you use the logic operator OR ||
, which means that either can be null and the while could still evaluate the statement. You need to use AND &&
to ensure yourself neither are null. Secondly, why would you not use a simple for-loop for this?
for (; mcl[i].getFirst_name() != null && mcl[i].getSurname() != null && i < mcl.Length(); i++)
{
useableCandidates[i]= mcl[i].getFirst_name()+" , "+mcl[i].getSurname();
}
Of course, if mcl[i]
does not exist for the specified i
, this will throw an ArrayOutOfBoundsException. It is important to check on this condition as well.
Upvotes: 4
Reputation: 784998
These conditions:
while(!mcl[i].getFirst_name().equals(null))
will give NullPointerException when mcl[i].getFirst_name()
returns null. Change it to:
while ( mcl[i].getFirst_name() != null && mcl[i].getSurname() != null )
Upvotes: 1