[ACCEPTED]-How to get line number using scanner-java.util.scanner

Accepted answer
Score: 17

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());
}

Score: 10

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

More Related questions