0

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;

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rangerguy
  • 69
  • 8
  • 1
    Clearly `students` or something in `students` is null. See http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – Radiodef May 16 '15 at 20:56
  • 3
    post the complete stack trace when you have exception; makes it easier for us to help. – Asura May 16 '15 at 20:59

1 Answers1

1

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;
}
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94