由于类成员,空指针异常

时间:2014-06-12 19:40:01

标签: java class nullpointerexception

public static void main(String args[]) throws IOException{
    String line = null;
    File newfile = new File("/home/aoblah/Documents/Metaphor/June12/X");
    File ex = new File("../June13/Test ID=ru002.txt");
    BufferedReader in = new BufferedReader(new FileReader(ex));
    PrintWriter wr = new PrintWriter(newfile);
    while((line = in.readLine()) != null){
        id = ex.getName();
        id = id.substring(0, id.indexOf("."));
        if(line.matches("^Sentence: [\\d]$")){
            sen_count ++;
        }
        if(line.contains(":Sentence:")){
            res_count ++;
    }

    }

    Sentence[] sen = new Sentence[sen_count];
    Results[] res = new Results[res_count];

    in = new BufferedReader(new FileReader(ex));

    sen_count = res_count = 0;

    while((line = in.readLine()) != null){
        if(line.matches("^Sentence: [\\d]$")){
            line = line.trim();
            a = line.split(": ");
            sen[sen_count].sentence_number = a[1];
            System.out.println(sen[sen_count].sentence_number);
        }
    }


}


公共课句{
public String sentence_number;
公共字句;
public Sentence(){
this.sentence = null;
this.sentence_number = null;
}

以上是结构和字符串" 1"被分配给sen [0] .sentence_number,我收到空指针异常。提取模式,当我将模式的一部分的值分配给一个简单的字符串时,它工作正常。将它分配给类成员时会发生异常。它表示我分配给它的值是在null变量上引用的。我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:1)

初始化数组不会初始化其成员。

您需要初始化其成员才能使用它们:

Sentence[] sen = new Sentence[sen_count];
for(int i=0; i<sen_count; i++) [
    sen[i] = new Sentence();
}

您必须对res

执行相同的操作