So, today I hit a snag trying to split a string array element which has been split from a long string already.. It works like this: A string is created from a file. This string is split at blank lines (\n\n) which are basically paragraphs of text, which gets used as body text elsewhere. Each paragraph begins with a topic, followed by an asterisk, followed by the body text. Here's the issue - It would be too simple to, while iterating through each paragraph string element to split these at the asterisk character (escaped, of course). To demonstrate, the first part works well:
sections = formatted.split("\n\n"); //sections previously declared as string array
int lines = sections.length ;
for(int i= 0 ; i< lines; i++) {
sections[i] = "Heading\n\n" + sections[i] ;
Now, when trying to perform another task in each iteration (yes, just join the two code windows together in your mind), it throws NPE on the second resulting index:
String paragraph = sections[i];
String[] half = paragraph.split("\\*");
topics[i] = half[0]; //Topics also previously declared as array
}
The last line inside the iterator throws a NPE (not out of bounds). I can't tell if it's the I or the ) index.
I would really appreciate understanding why this doesn't work. Perhaps it's because I always seem to hit these problems well after midnight...
How can I build these two parallel instance arrays? Thanks!
It seems likely to me that Topics
is null - there's nothing within the code you've shown to assign it a non-null value. You probably want:
Topics = new String[lines];
before the loop. You should be able to spot this pretty easily in the debugger, too. (If you're confused about where an NPE is coming from, adding diagnostics and/or debugging are usually the first steps.)
Also note that conventionally your variables would be called sections
and topics
, as variables in Java are usually camelCased.
See more on this question at Stackoverflow