[ACCEPTED]-How to get line number using scanner-java.util.scanner
Accepted answer
You could use a LineNumberReader
in place of the BufferedReader
to keep 4 track of the line number while the scanner 3 does its thing.
LineNumberReader r = new LineNumberReader(new FileReader("input.txt"));
String l;
while ((l = r.readLine()) != null) {
Scanner s = new Scanner(l);
while (s.hasNext()) {
System.out.println("Line " + r.getLineNumber() + ": " + s.next());
}
}
Note: The "obvious" solution 2 I first posted does not work as the scanner 1 reads ahead of the current token.
r = new LineNumberReader(new FileReader("input.txt"));
s = new Scanner(r);
while (s.hasNext()) {
System.out.println("Line " + r.getLineNumber() + ": " + s.next());
}
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());
}
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.