我有一个包含以下内容的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."
知道这里发生了什么吗?
答案 0 :(得分:4)
您实际上并未阅读文件。
您需要将扫描程序声明为new Scanner(new File("test.txt"));
否则,扫描程序会扫描字符串“test.txt”以获取Mary。
请参阅Scanner doc了解不同的构造函数
答案 1 :(得分:0)
vandale是正确的,new Scanner("test.txt")
应为new Scanner(new File("test.txt"))
。
但是,如果要查找包含单词“Mary”的行数,则需要稍微更改一下代码。看看带注释的行:
import java.util.Scanner;
import java.io.*;
class Test {
public static void main(String[] blargs) {
int count = 0;
Scanner reader = new Scanner(new File("test.txt"));
while (reader.hasNextLine()) {
String nextToken = reader.nextLine(); // nextLine() instead of next().
if (nextToken.contains("Mary")) // contains() instead of equals()
count++;
}
System.out.println("The word 'Mary' was found on " + count + " lines.");
}
}