Reputation:
I'm trying to read text inside a .txt document using console command java program < doc.txt
. The program should look for words inside a file, and the file CAN contain empty new lines, so I've tried changing the while condition from:
while((s = in.nextLine()) != null)
to:
while((s = in.nextLine()) != "-1")
making it stop when it would have found -1
(I've also tried with .equals()
), but it does not work. How can I tell my program to stop searching for words when there's no more text to examine? Otherwise it keeps stopping when it finds an empty string (newline alone or sequence of new lines).
I've only found solutions using BufferedReader
, but I don't know how to use it in this situation where the file is being read by the console command java program < doc.txt
.
I post the code inside the while, if it can be necessary:
while((s = in.nextLine()) != null) {
s = s.toLowerCase();
Scanner line = new Scanner(s);
a = line.next();
if(a.equals("word")) {
k++;
}
}
Upvotes: 1
Views: 1207
Reputation: 727097
Proper way of figuring out when Scanner
runs out of input is checking hasNextLine()
condition. Use this loop to read a sequence of strings that includes empty lines:
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
String s = in.nextLine();
System.out.println(s);
}
Upvotes: 2