【发布时间】:2013-10-13 19:08:15
【问题描述】:
我创建了一个简单的扫描器来计算 .txt 文件中的字符串数。每个字符串都在 nextLine。它算错了,每次它给我的数字是 297,即使有超过 20 000 个字符串。 .txt 文件是由我编写的另一个程序创建的,它从网站获取链接并将它们与 FileWriter 和 BufferedWriter 一起保存到 .txt 文件中。有什么问题?
public class Counter {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
String string = scanner.next();
int count = 0;
while (scanner.hasNextLine()) {
string = scanner.next();
count++;
System.out.println(count);
}
}
}
编辑:字符串示例:
yahoo.com
google.com
etc.
【问题讨论】:
-
"超过 20 000 个字符串" 你确定超过 20000 行吗?
-
链接之类的字符串。是的,我确定 - 我已经在 MS Word 中数过了。
-
尝试使用
scanner.hasNext()看看会发生什么。 -
看起来不太好的一件事是,当您声明
String string时,您正在阅读scanner.next();并且不计算它。另一件事是,如果你想计算有多少行,你应该使用nextLine,而不是next。 -
你不需要
String string = scanner.next,只需要String string;