3

I am trying to delete a field in an array. The array contains objects of type Person (Person contains firstname, lastname, birthdate and ID).

My intention was to look up each array field and compare the input ID with all the array fields. When I find the right one, I will set it to null.

But I get:

Exception in thread "main" java.lang.NullPointerException

And I don't know why.

public static void removePerson(Person[] container) {
    TextIO.putln("Enter ID of person to be removed");
    int index = TextIO.getInt();

    for ( int i = 0 ; i < container.length ; i ++) {
        if (container[i].id == index)
            container[i] = null;
    }
}
2
  • In all likelihood, one of container's elements are null. We can't help with only the code you gave us, as container isn't set up there. Please provide us with an SSCCE (Short, Self Contained, Correct (Compilable), Example). Commented Jan 9, 2014 at 22:32
  • 2
    Just print all stacktrace and you will find out the reason. You should change this line: if (container[i].id == index) to if (container[i] != null && container[i].id == index). Commented Jan 9, 2014 at 22:38

2 Answers 2

3

The most likely case is your array isn't full, so some container array entries are null, and container[i].id is what triggers the null pointer exception. Replace your test with

if ((container[i] != null) && (container[i].id==index))

and see if that fixes your problem.

Sign up to request clarification or add additional context in comments.

Comments

2

The problem is due to the row

 container[i].id == index

when you have already "removed" (marked null) a previous container you could get a NullPointerException

replace to

  if (container[i]!=null && container[i].id == index)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.