Rangerguy
Rangerguy

Reputation: 69

Deleting an element in array

This keeps throwing a NullPointerException after the if statement, do any of you have an idea why?

public void deleteCourse() {

    Scanner courseInput = new Scanner(System.in);
    System.out.println("Enter coursename to delete");
    String deleteInput = courseInput.nextLine();
    System.out.println("check");
    int pos = this.findPosition(deleteInput);
    System.out.println(pos);
    if (pos != -1) {

        students[pos].setName(students[students.length - 1].getName());
        students[pos].setGrade(students[students.length - 1].getGrade());

    }

}

public int findPosition(String deleteInput) {
    int i;
    for (i = 0; i < students.length; i++) {

        if (deleteInput.equals(students[i].getName())) {
            return i;
        }

    }

    return -1;

}

Upvotes: 0

Views: 68

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

At least one of the values of the array students has not been set by you and is null. When you try to access the element that is null via getName(), you get the NullPointerException.

To prevent this, simply skip the elements that are null:

public int findPosition(String deleteInput) {
    if(deleteInput == null) {
        return -1;
    }

    for (int i = 0; i < students.length; i++) {

        if (students[i] != null && deleteInput.equals(students[i].getName())) {
            return i;
        }

    }
    return -1;
}

Upvotes: 1

Related Questions