0

我有一个包含以下内容的 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."

知道这里发生了什么吗?

4

2 回答 2

4

您实际上并没有从文件中读取。

您需要将扫描仪声明为new Scanner(new File("test.txt"));否则,扫描仪实际上是在为 Mary 扫描字符串“test.txt”。

有关不同的构造函数,请参阅Scanner文档

于 2013-11-03T00:19:47.933 回答
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.");
    }
}
于 2013-11-03T00:25:01.110 回答