I’m reading in a text file formated like
JavaScript
x
word
definiton
word
definition
definition
word
definition
So I need to keep try of whether I’m in a definition or not based on when I reach those emtpy lines. Thing is, BufferedReader
discards n
characters, and somehow comparing that empty line to String ""
is not registering like I thought it would. How can I go about doing this.
Advertisement
Answer
- Make sure you use:
"".equals(myString)
(which isnull
-safe) notmyString == ""
.- After 1.6, you can use
myString.isEmpty()
(notnull
-safe)
- After 1.6, you can use
- You can use
myString.trim()
to get rid of extra whitespace before the above check
Here’s some code:
JavaScript
public void readFile(BufferedReader br) {
boolean inDefinition = false;
while(br.ready()) {
String next = br.readLine().trim();
if(next.isEmpty()) {
inDefinition = false;
continue;
}
if(!inDefinition) {
handleWord(next);
inDefinition = true;
} else {
handleDefinition(next);
}
}
}