How to get line number using scanner

前端 未结 2 1705
渐次进展
渐次进展 2020-12-11 16:47

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:



        
2条回答
  •  执笔经年
    2020-12-11 17:24

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

提交回复
热议问题