返回空指针错误的方法

时间:2013-11-15 16:54:10

标签: java

我有错误

  Exception in thread "main" java.lang.NullPointerException
  at StudentGrades.getMinimum(StudentGrades.java:54)
  at StudentClient.main(StudentClient.java:14)

我没有找到任何设置null的方法。

我尝试使用中值方法,但仍然得到了同样的错误。

import java.util.Arrays;
import java.util.Random;

public class StudentGrades {

Random randomNumber = new Random();
int numberofStudents;
int grade;
int[] grades;
int sum = 0;

public StudentGrades(int studentNumber) {
    numberofStudents = studentNumber;
    int[] grades = new int[numberofStudents];
    for (int i = 0; i < numberofStudents; i++) {
        grades[i] = randomNumber.nextInt(101);
        Arrays.sort(grades);

    }

}

public int getNumberStudents() {
    return numberofStudents;
}

public int[] getStudentGrades() {
    int[] temp = new int[grades.length];
    for (int i = 0; i < grades.length; i++) {
        temp[i] = grades[i];
    }
    return temp;
}

public void setStudentGrades(int n) {
    grade = n;
}

public double getAverage() {
    for (int i = 0; i < grades.length; i++) {
        sum = +grades[i];
    }
    double average = (double) sum / numberofStudents;
    return average;
}

public int getMaximum() {
    int max = grades[0];
    for (int i = 0; i < grades.length; i++) {
        if (grades[i] > grades[max])
            max = grades[i];
    }
    return max;

}

public int getMinimum() {
    int min = grades[0];
    for (int i = 0; i < grades.length; i++) {

        if (grades[i] < grades[min])
            min = grades[i];
    }
    return min;
}

public String toString() {
    String returnString = "grades :";
    for (int i = 0; i < grades.length; i++) {
        returnString += grades[i];
    }
    return returnString;
}

public double getMedian() {
    double median = 0;

    if (grades.length % 2 == 0) {
        median = (grades[grades.length / 2] + grades[(grades.length / 2) + 1]) / 2;

    } else

        median = grades[((grades.length - 1) / 2) + 1];

    return median;
}

}

1 个答案:

答案 0 :(得分:2)

在您的构造函数中,您声明了一个本地变量grades,该变量未初始化您的实例变量grades

int [] grades = new int [numberofStudents];

因此,实例变量grades仍为null。试试这个:

grades = new int [numberofStudents];

引用实例变量而不是声明局部变量。