4

我有一个问题,我试图创建一个应用程序来计算文件中符号的所有出现次数......扫描仪方法“nextLine”在一个空行处停止......有没有办法让它继续运行直到它到达文件的真正结尾?

简而言之:我可以获得文件中的真实行数吗?

先感谢您!

4

3 回答 3

6

您可以使用循环:

int count = 0;
while (scanner.hasNextLine()) {
    count++;
    scanner.nextLine();
}

count将包含行数。

于 2013-09-19T18:54:28.637 回答
1

So I've been doing some research about this problem. I've been coming up against it recently while writing a line counting program in Java for the class I'm taking.

The reason the scanner class does this is because scanner.next() and scanner.nextLine() return tokens, which are separated by delimiters. By default the delimiter is whitespace. So what's happening is that when you call scanner.hasNext() or scanner.hasNextLine() is that it looks to see if there is a token after the next delimiter. When a file ends in a newline character, there is no token after that, so hasNext() and hasNextLine() return false.

As far as I can tell, to do what you want you'd need to count the number of delimiters, which is better handled in Martinus's answer. See also AFinkelstein's answer.

于 2014-01-22T05:29:08.520 回答
0

请参阅Scanner.hasNextLine(),您可能应该在循环条件中使用它。如果它更适合您的需求,还有一个Scanner.hasNext() 。

于 2013-09-19T18:58:04.310 回答