删除数组中的元素

时间:2015-05-16 20:54:47

标签: java arrays element

这会在if语句后继续抛出NullPointerException,你们中的任何人都知道为什么会这样做吗?

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;

}

1 个答案:

答案 0 :(得分:1)

您尚未设置数组students的至少一个值,并且nullnull。当您尝试通过getName()访问NullPointerException元素时,您会获得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; }

元素即可
SSLCipherSuite