如何使用扫描仪获取行号 [英] How to get line number using scanner

查看:119
本文介绍了如何使用扫描仪获取行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用扫描仪逐行读取文本文件但是如何获取行号,因为扫描程序遍历每个输入?我的程序是这样的:

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

这样可行,但例如:


1,2,3 
3,4,5

我想知道行号它意味着1,2,3在第1行,3,4,5在第2行。我怎么做到?

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?

推荐答案

您可以使用 LineNumberReader 代替 BufferedReader ,以便在扫描仪完成任务时跟踪行号。

You could use a LineNumberReader in place of the BufferedReader to keep track of the line number while the scanner 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 I first posted does not work as the scanner 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());
}

这篇关于如何使用扫描仪获取行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆