输入字符串问题

时间:2011-03-11 12:08:37

标签: java

System.out.println("Please enter the required word  :");
    Scanner scan2 = new Scanner(System.in);
    String word2 = scan2.nextLine();
    String[] array2 = word2.split(" ");

    for (int b = 0; b < array2.length; b++) {
        int numofDoc = 0;

        for (int i = 0; i < filename; i++) {

            try {

                BufferedReader in = new BufferedReader(new FileReader(
                        "C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
                                + i + ".txt"));

                int matchedWord = 0;

                Scanner s2 = new Scanner(in);

                {

                    while (s2.hasNext()) {
                        if (s2.next().equals(word2))
                            matchedWord++;
                    }

                }
                if (matchedWord > 0)
                    numofDoc++;

            } catch (IOException e) {
                System.out.println("File not found.");
            }

        }
        System.out.println("This file contain the term  " + numofDoc);
    }
}

}

这是我用于计算包含特定术语的文档数量的代码。例如 : 假设我有1000万个文本文件,其中一千个中出现字符串COW。我正在寻找包含COW字符串的总共一千个文档。

我的程序目前只能处理一个字符串输入。

我的程序输出是:

COW

包含此术语的文件为1000.

我现在面临的问题是当我输入3个字符串时,它无法处理3个字符串。例如:

COW很好

包含此术语的文件为0。

包含此术语的文件为0。

包含此术语的文件为0.

我一整天都在尝试,但我不知道我的错误在哪里。介意指出我的错误?

2 个答案:

答案 0 :(得分:0)

问题在于:

if (s2.next().equals(word2))

如果word2 = "I love you"并且您正在执行equals()s2.next() 必须包含单词I love you

解决此问题的一种方法。

String[] words = word2.split(" ");
for (String word: words) {
    if (s2.next().equals(word)) {
        matchedWord++;
    }
}

答案 1 :(得分:0)

根据你的代码,你做了一个循环3次(array2.length),但你根本不使用array2,而是你找三次字符串“COW IS GOOD”。您应该将行s2.next().equals(word2)更改为s2.next().equals(array2[b])