我有一个包含以下内容的txt文件:
Mary had a little lamb little lamb
little lamb. Mary had a little lamb.
That's all? Did the lamb follow Mary
wherever Mary went?
我正在尝试编写一些代码,以扫描txt文件中的单词“玛丽”,计算出现的次数,然后打印该数字。
import java.util.Scanner;
import java.io.*;
class Test {
public static void main(String[] args) {
int count = 0;
Scanner reader = new Scanner("test.txt");
while (reader.hasNextLine()) {
String nextToken = reader.next();
if (nextToken.equals("Mary"))
count++;
}
System.out.println("The word 'Mary' was found on " + count + " lines.");
}
}
代码编译时,我一直输入错误,系统打印
"The word 'Mary' was found on 0 lines."
知道这里发生了什么吗?
最佳答案
您实际上不是从文件中读取。
您需要将扫描仪声明为new Scanner(new File("test.txt"));
,否则,扫描仪将在字面上扫描Mary的字符串“ test.txt”。
有关不同的构造函数,请参见Scanner文档
关于java - 尝试扫描txt文件中的特定单词时发生逻辑错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19748457/