Java程序中的Java.lang.NullPointerException错误

时间:2014-02-05 03:30:03

标签: java pointers methods null

继续收到此错误,抱歉我是Java的初学者。

  

线程“main”中的异常:java.lang.NullPointerException
  在assignment01.Student.addGrade(Student.java:28)
  在assignment01.GpaTest.main(GpaTest.java:11)​​

package assignment01;

    public class Grades 
    {
        private double qualPts;
        private int numCred;

        public double getGPA()
        {
            if(numCred!=0)
            {
                return(qualPts/numCred);
            }
            return numCred;  
        }

        public void addGrade(int creds, double grade)
        {
            grade+=creds+numCred;
            qualPts+=creds*grade;
        }

        public int getNumCred()
        {
            return numCred;
        }
    }

package assignment01;

public class Student 
{
    private String name;
    private String bNumber;
    private Grades grades; 

    public Student(String name, String bNumber)
    {
        this.name=name;
        this.bNumber=bNumber;
    }

    public void addGrade(int creds, double grade)
    {   
        grades.addGrade(creds, grade);

    }

package assignment01;

public class GpaTest {

    public static void main(String[] args)
    {
        Student theStudent= new Student("Ethan","00000000");
        int CREDITS_ENROLLED1=4;
        double GRADE1=90;
        theStudent.addGrade(1, 100);
        theStudent.addGrade(CREDITS_ENROLLED1,GRADE1);
        System.out.println("Determining the grades of student named Ethan.");   
        System.out.println("Ethan has a grade of 90.");
    }
}

2 个答案:

答案 0 :(得分:4)

grades变量未初始化。您需要在Student构造函数中初始化它:

public Student(String name, String bNumber)
{
  this.name=name;
  this.bNumber=bNumber;
  this.grades = new Grades();
}

您可能希望初始化qualPtsnumCred

答案 1 :(得分:0)

初始化对象'成绩'。