Iterator help
publicvoid addStudent(String name,int number, String course)
{
Iterator<Student> it = students.iterator();
while(it.hasNext())
{
Student temp = it.next();
if (temp.getName().equals(name))
{
System.out.println("Sorry, student already there.");
}
else
{
students.add(new Hons(name, number, course,null));
}
}
}
I have the above code and it compiles just I can't get it to run.
When it runs I get a null pointer.
Anyone got any ideas?
Thanks.
[1067 byte] By [
gh.tommo7a] at [2007-11-27 1:20:02]

Well since we don't have the line number, maybe we can help you find the problem another way. NullPointerExceptions are usually thrown when a method is called on a Null object. So looking at the code I can guess a few areas for a null pointer exception:
1. students.iterator() - if the students collection is null, you'll get the exception here
2. temp.getName().equals(name) - temp shouldn't be null since the itereator told you it had something, but the result of getName() certainly could be null
3. new Hons(name, number, course, null) - without the code for the Hons class it's tough to tell if anything funky is goin on, but it could be.
Anyway, #2 seems most likely since I assume you are actually setting students to something. And since you should have the line number or a better idea of which of the above is the problem, don't be afraid to add code to your program to test for null. It needn't remain if it is just revealing an error somewhere else but something like this can at least tell you what is happening:
if (temp.getName() == null)
System.out.println("doh!");