Array null pointer exception error

后端 未结 2 865
甜味超标
甜味超标 2020-12-20 21:37

I am continuing with my project for school and have seemed to encounter another error. So what is happening is basically I am receiving a null pointer exception even though

2条回答
  •  不思量自难忘°
    2020-12-20 22:12

    As your code is currently written,

    System.out.println(studentArray[0].getFirstName());
    

    Will throw an NPE since you're never initializing the array.

    private static students[] studentArray;
    

    Just declares it, doesn't initialize it.

    Maybe you should refactor your code as follows

    private static ArrayList studentArray = new ArrayList();
    
    // Inside the constructor or some method called before you access studentArray:
    studentArray.add(stu1);
    studentArray.add(stu2);
    //...
    
    // or, more concisely, since you're not using the temporary `students` variables:
    studentArray.add(new students(65435, "Bob", "Ted"));
    studentArray.add(new students(45546, "Guy", "Sid"));
    //...
    

    If you're committed to using an array and not a List,

    private static students[] studentArray;
    

    needs to be initialized with something like

    private static students[] studentArray = new students[10];
    

    and then you need to assign its elements

    studentArray[0] = stu1;
    

    or

    studentArray[0] = new students(65435, "Bob", "Ted");
    

提交回复
热议问题