-4
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 class Sentence{
public String sentence_number;
public String sentence;
public Sentence(){
this.sentence = null;
this.sentence_number = null;
}

Above is the structure and a string "1" is assigned to sen[0].sentence_number where I receive a null pointer exception. The pattern is extracted and when I assign the value of part of the pattern to a simple string, it works fine. The exception occurs when I assign it to the class member. It says that the value I am assigning it to, is referenced on a null variable. How do I fix this?

Thanks.

dirdir69
  • 47
  • 7

1 Answers1

1

Initializing an array will not initialize its members.

You need to initialize its members in order to work with them:

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

You'll have to do the same with res

BackSlash
  • 21,927
  • 22
  • 96
  • 136