tags:

views:

556

answers:

2

I'm using scanner to read a text file line by line but then how to get line number since scanner iterates through each input?My program is something like this:

s = new Scanner(new BufferedReader(new FileReader("input.txt")));

while (s.hasNext()) {
System.out.print(s.next());

This works fine but for example:

1,2,3 
3,4,5

I want to know line number of it which mean 1,2,3 is in line 1 and 3,4,5 is in line 2.How do I get that?

+6  A: 
John Kugelman
Thanks but this is not working. Line number does not change eventhough it's in new line
gingergeek
post your code?
Chii
A: 

Just put a counter in the loop:

s = new Scanner(new BufferedReader(new FileReader("input.txt")));

for (int lineNum=1; s.hasNext(); lineNum++) {
   System.out.print("Line number " + lineNum + ": " + s.next());
}
Ry4an
I think this only works if you have .useDelimiter() set to newline. If you scan for whitespace (e.g. words) than it will count words instead.
Roalt