Java – stringreader from string Error given in split output
An exception occurred while using stringreader When creating an object, the string I parse is through string Split generated, which gave me NullPointerException Any suggestions on how to solve this problem?
This is the code:
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);
}
}
}
And docreader classes
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();
}
}
}
Exceptions:
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 result: 1
When I check line 50 in the stringreader class, it contains
this.length = s.length();
Solution
In this part of the code:
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);
}
You are using J, so the value of J increases by 1, then you have this Code:
String temp=reader.sentences[i][j];
Because this new entry in the array is different from null, it may contain a null value, which is assigned to temp to initialize stringreader and take null value as parameter
One way to solve it is to add J. after using it to build a stringreader. In addition, in the current form, if reader If all values of senses [i] are not null, this code may also throw ArrayIndexOutOfBoundsException This will be the solution to the above 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++;
}
