如何修复“ java.lang.NullPointerException”

时间:2019-07-01 21:30:38

标签: java class object

问题是我的“ studentList [X] .setID(studentID)”返回NullPointerException。您无法创建对象数组吗?还是有未声明的东西?

我重新检查了方法是否正确填写。我还检查了主要部分是否有意义。

package Problem1;
import java.util.Scanner;



public class Problem2 {
    public static void main(String[] args) {


    double studentID;
    String aFullName, aMajor;



    Student [] studentList  = new Student[3];

    //list
    Scanner in = new Scanner(System.in);

    //Student 1
    System.out.println("Enter in Student 1's student ID: ");
        studentID = in.nextDouble();
        in.nextLine();

    System.out.println("Enter in Student 1's full name: ");
        aFullName = in.nextLine();


    System.out.println("Enter in Student 1's major: ");
        aMajor = in.nextLine();


    studentList[0].setID(studentID);
    studentList[0].setFullName(aFullName);
    studentList[0].setMajor(aMajor);

    //Student 2
    System.out.println("Enter in Student 2's student ID: ");
        studentID = in.nextDouble();
        in.nextLine();

    System.out.println("Enter in Student 2's full name: ");
        aFullName = in.nextLine();


    System.out.println("Enter in Student 2's major: ");
        aMajor = in.nextLine();

    studentList[1].setID(studentID);
    studentList[1].setFullName(aFullName);
    studentList[1].setMajor(aMajor);    

    //Student 3
    System.out.println("Enter in Student 3's student ID: ");
        studentID = in.nextDouble();
        in.nextLine();

    System.out.println("Enter in Student 3's full name: ");
        aFullName = in.nextLine();


    System.out.println("Enter in Student 3's major: ");
        aMajor = in.nextLine();

    studentList[2].setID(studentID);
    studentList[2].setFullName(aFullName);
    studentList[2].setMajor(aMajor);    


    System.out.println("All information collected.");

    for(int i = 0; i < studentList.length; i++)
    {
        studentList[i].StudentDisplayer();
    }


}


static class Student {                      //attributes
    private double studentID;
    private String fullName; 
    private String major;


    void StudentDisplayer() {
        System.out.println(studentID + " " + fullName + " " + major);
        return;
    }
    /*
    //GET METHODS
    public double getID() 
    { 
        //double number = ISBNum;
        return studentID; 
    } 

    // method 2 
    public String getFullName() 
    { 
        return fullName; 
    } 

    // method 3 
    public String getMajor() 
    { 
        return major; 
    } 

    */

    //SET METHODS
    public void setID(double aID)
    {
        studentID = aID;
        return;
    }


    public void setFullName(String aName)
    {
        fullName = aName;
        return;
    }

    public void setMajor(String aMajor)
    {   
        major = aMajor;
        return;
    }



}
}

我能够通过: “输入学生1的ID” “输入全名” “输入专业”

但是在那之后我遇到了NullPointerException。

0 个答案:

没有答案