使用StringReader时出现异常。创建对象时解析的字符串是通过String.split生成的,它给了我NullPointerException。任何建议如何解决这个问题?

这是代码:

public static void main(String[] args) throws IOException {
    // TODO code application logic here
    int jmldoc = 5;
    Hashmap hashsentences[][] = new Hashmap[5][100];
    Docreader reader = new Docreader();
    System.out.println(reader.doc[1]);

    for (int i = 0; i < jmldoc; i++) {
        int j = 0;
        while (reader.sentences[i][j] != null) {
            System.out.println(reader.sentences[i][j]);
            j++;
            String temp=reader.sentences[i][j];
            StringReader h = new StringReader(temp);

        }
    }


}

和docreader类
    public class Docreader {

    public String sentences[][]=new String[5][100];
    public String doc[]=new String[5];

    public Docreader() throws IOException{

    this.readdoc();
    this.splittosentence();

    }

   public void readdoc() throws IOException {
        for (int i = 0; i < 5; i++) {
            String temp = new String();
            temp = Docreader.readFile("datatrain/doc" + (i + 1) + ".txt");
            this.doc[i] = temp;
        }

    }

    public void splittosentence() {


        for (int i = 0; i < 5; i++) {
            String temp[];
            temp = doc[i].split("\\.");
            for(int j=0;j<temp.length;j++){
            sentences[i][j]=temp[j];

            }

        }

    }

    private static String readFile(String fileName) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            return sb.toString();
        }
    }
}

例外:
Exception in thread "main" java.lang.NullPointerException
at java.io.StringReader.<init>(StringReader.java:50)
at stki_d_8_final.STKI_D_8_Final.main(STKI_D_8_Final.java:45)

Java结果:1

当我在StringReader类中检查第50行时,它包含
this.length = s.length();

最佳答案

在这部分代码中:

while (reader.sentences[i][j] != null) {
    System.out.println(reader.sentences[i][j]);
    j++;
    String temp=reader.sentences[i][j];
    StringReader h = new StringReader(temp);
}

您正在使用j++,因此j的值增加1,那么您将获得以下代码:
String temp=reader.sentences[i][j];

由于尚未评估数组中的此新条目是否不同于null,因此它可能包含null值,该值已分配给temp并因此使用StringReader值作为参数来初始化null

解决该问题的一种方法是在使用j构建StringReader之后增加ArrayIndexOutOfBoundsException。同样,如果reader.sentences[i]的所有值都不是null,则以当前形式,此代码也可能抛出ojit_code。这将是上面代码的解决方案:
while (j < reader.sentences[i].length && reader.sentences[i][j] != null) {
    System.out.println(reader.sentences[i][j]);
    String temp=reader.sentences[i][j];
    StringReader h = new StringReader(temp);
    j++;
}

09-26 18:29