I’m going through a .txt file that has blank lines between lines of text.
I have a scanner that takes each line and gives that to a 2nd scanner that gets each word from the line.
The problem I have, is that if I hit an empty line, the first scanner is getting null input for it’s .nextLine().
How can I make sure that:
-
I have more text remaining (and not just empty lines), It would probably be easier to just make a separate boolean to check this.
-
If the boolean checks out fine, then to just skip those empty lines and pass the 2nd scanner the text in the lines that actually contain text.
My attempt so far has been this:
Scanner one //scans each line from file
Scanner two //scans each word from scanner one
public boolean more() {
if (two.more()) {
return true;
} else if (one.hasNext()) {
two = new Scanner(one.nextLine());
return this.more();
} else {
return false;
}
}
public String getText() {
String text = "";
if(two.hasNext()) {
text = two.next();
} else {
while(!one.hasNext()) {
one.nextLine();
}
two = new Scanner(one.NextLine());
text = two.next();
}
return text;
}
A simple solution is to trim the line you get from the first Scanner and then only pass it to the second Scanner if it isn’t empty. For instance:
Tested on this file:
ScannerTest.txt
Output: