带有2d数组和对象的空指针

时间:2013-10-13 18:54:49

标签: java nullpointerexception

您好我正在创建一个包含多个类的项目来创建进度报告。但是我正在测试方法,但尚未完成项目并遇到空指针异常。看看代码,看看你是否可以帮助我。请记住,所有方法都没有完成,只是首先关注我的问题。我还有一个单独的驱动程序文件,除非另有需要,否则我找不到帖子。

学生班级:

public class Student {
private String name;
private char grade;
private double average;
private int[] scores = new int[5];

// Constructor
public Student() {
    this.name = name;
    this.grade = grade;
    this.average = average;
    this.scores = scores;
}


// Get the Name.
public String getName() {
    return name;
}

// Set the Name.
public void setName(String name) {
    this.name = name;
}

// Get the Grade.
public char getGrade() {
    return grade;
}

// Set the Grade.
public void setGrade(char grade) {
    this.grade = grade;
}

// Get the Average.
public double getAverage() {
    return average;
}

// Set the Average.
public void setAverage(double average) {
    this.average = average;
}

// Get the Scores.
public int[] getScores() {
    return scores;
}

// Set the Scores.
public void setScores(int[] scores) {
    this.scores = scores;
}

// Determine the average of the five test scores for each student
public void calculateAverage(){

}

public void calculateGrade(){

}
}

ProgressReport class (我得到空指针异常)

public class ProgressReport {
// Create array to hold sections and students.
Student[][] sectionArray = new Student[2][];

// Constructor.
public ProgressReport() {

}

// Get sectionArray.
public Student[][] getSectionArray() {
    return sectionArray;
}

// Set sectionArray.
public void setSectionArray(Student[][] sectionArray) {
    this.sectionArray = sectionArray;
} 

// Read the input file.
public void readInputFile() throws FileNotFoundException{
    String line;
    int studentNo;
    // Open file
    File inFile = new File("file.in");
    // Create scanner for reading.
    Scanner scanner = new Scanner(inFile);
    // While inFile has more lines.
    while(scanner.hasNext()){
        // Read the next line.
        line = scanner.nextLine();
        // Trim line.
        line = line.trim();
        //Parse line into int.
        studentNo = Integer.parseInt(line);
        // For the number of students in section 1 extract data.
        for(int i = 0; i<= studentNo; i++){
            //Create new student.
            sectionArray[0][i] = new Student(); **THIS IS WHERE I GET NULL POINTER EXCEPTION**
            // Read next line.
            line = scanner.nextLine();
            // Create String Tokenizer using a space as the delimiter.
            StringTokenizer strTokenizer = new StringTokenizer(line," ");
            // While the String Tokeizer has more tokens get data.
            while(strTokenizer.hasMoreTokens()){
                // Extract name
                String name = strTokenizer.nextToken();
                // Set name
                sectionArray[0][i].setName(name);

                int[] scores = new int[5];
                // Extract scores.
                int score1 = Integer.parseInt(strTokenizer.nextToken());
                int score2 = Integer.parseInt(strTokenizer.nextToken());
                int score3 = Integer.parseInt(strTokenizer.nextToken());
                int score4 = Integer.parseInt(strTokenizer.nextToken());
                int score5 = Integer.parseInt(strTokenizer.nextToken());
                //Put scores in scores array.
                scores[0] = score1;
                scores[1] = score2;
                scores[2] = score3;
                scores[3] = score4;
                scores[4] = score5;
                // Set scores.
                sectionArray[0][i].setScores(scores);   

            }
        }
    }
}

// Generate a report.
public void generateReport(){
    System.out.println("Progress Report\n");
    System.out.println("Section 1");
    System.out.println(sectionArray[0][0].getName());
}

// Sort by name.
public void sortByName(){

}

// Binary search.
public Student binarySearch(int section, String searchName){
    return null;

}

}

我不是要求任何人完成我的工作,只是解释为什么我会得到一个空指针异常。

4 个答案:

答案 0 :(得分:3)

一旦您知道Student的数量为

,就需要初始化第二个维度
    studentNo = Integer.parseInt(line);

    // initialize the Array
    sectionArray[0] = new Student[studentNo];

    // For the number of students in section 1 extract data.
    for(int i = 0; i<= studentNo; i++){

您始终将sectionArray用作sectionArray[0][*]。我不确定你是否真的需要这个阵列是二维的。将其初始化为new Student[2][];表示您在某个时间点也会使用sectionArray[1][*]

如果你以后这样做;您还需要初始化sectionArray[1]

答案 1 :(得分:1)

如果你这样做

String[][] array = new String[2][];

它将创建一个具有两个null元素的数组,因此它与

相同
String[][] array = {null,null};

并且由于您在此类数组上调用sectionArray[0][i],因此它与调用引发NPE的null[i]相同。

答案 2 :(得分:0)

您需要指定两个维度:Student[][] sectionArray = new Student[2][2];或初始化第二个维度,如下所示:sectionArray[0] = new Student[students];sectionArray[1] = new Student[students];

答案 3 :(得分:0)

那么你在这里使用数组数组用于学生类。

对于每个(数组数组)数组,您需要使用所需的数字启动每个数组 元素。

这里: 在这一行之前...你得到Null指针异常,

sectionArray [0] [i] = new Student();

你需要用这样的新关键字启动数组sectionArray [0]。

sectionArray[0]= new Student[studentNo];             // add this line to you code

然后您使用的代码将会出现。