我有一个包含以下内容的 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 文件中的单词“Mary”,计算它出现的次数,然后打印该数字。
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."
知道这里发生了什么吗?