Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查文件中单词列表的最有效方法_Java_Hashtable_Hashset_Treeset - Fatal编程技术网

Java 检查文件中单词列表的最有效方法

Java 检查文件中单词列表的最有效方法,java,hashtable,hashset,treeset,Java,Hashtable,Hashset,Treeset,我刚刚有一个家庭作业,要求我将所有Java关键字添加到一个哈希集中。然后读入一个.java文件,并计算任何关键字在.java文件中出现的次数 我走的路线是: 创建了包含所有关键字的字符串[]数组。 创建了一个哈希集,并使用Collections.addAll将数组添加到哈希集。 然后,当我遍历文本文件时,我会通过HashSet.contains(currentWordFromFile)检查它 有人建议使用哈希表来执行此操作。然后我看到了一个使用树集的类似示例。我只是好奇。。推荐的方法是什么 (此

我刚刚有一个家庭作业,要求我将所有Java关键字添加到一个哈希集中。然后读入一个.java文件,并计算任何关键字在.java文件中出现的次数

我走的路线是: 创建了包含所有关键字的字符串[]数组。 创建了一个哈希集,并使用Collections.addAll将数组添加到哈希集。 然后,当我遍历文本文件时,我会通过HashSet.contains(currentWordFromFile)检查它

有人建议使用哈希表来执行此操作。然后我看到了一个使用树集的类似示例。我只是好奇。。推荐的方法是什么

(此处完整代码:)

尝试一个
映射,其中字符串是单词,整数是单词被看到的次数

这样做的一个好处是,您不需要处理文件两次。

您说“有家庭作业”,所以我假设您已经完成了

我会做得有点不同。首先,我认为您的
字符串
数组中的一些关键字不正确。根据和,Java有50个关键字。无论如何,我对代码的注释相当好。这是我想到的

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public class CountKeywords {

    public static void main(String args[]) {

        String[] theKeywords = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" };

        // put each keyword in the map with value 0 
        Map<String, Integer> theKeywordCount = new HashMap<String, Integer>();
        for (String str : theKeywords) {
            theKeywordCount.put(str, 0);
        }

        FileReader fr;
        BufferedReader br;
        File file = new File(args[0]);

        // attempt to open and read file
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);

            String sLine;

            // read lines until reaching the end of the file
            while ((sLine = br.readLine()) != null) {

                // if an empty line was read
                if (sLine.length() != 0) {

                    // extract the words from the current line in the file
                    if (theKeywordCount.containsKey(sLine)) {
                        theKeywordCount.put(sLine, theKeywordCount.get(sLine) + 1);
                    }
                }
            }

        } catch (FileNotFoundException exception) {
            // Unable to find file.
            exception.printStackTrace();
        } catch (IOException exception) {
            // Unable to read line.
            exception.printStackTrace();
        } finally {
                br.close();
            }

        // count how many times each keyword was encontered
        int occurrences = 0;
        for (Integer i : theKeywordCount.values()) {
            occurrences += i;
        }

        System.out.println("\n\nTotal occurences in file: " + occurrences);
    }
}
。。。最后你把计数器打印出来

我不知道这是否是最有效的方法,但我认为这是一个坚实的开端

如果你有任何问题,请告诉我。我希望这有帮助。

Hristo

这种方法似乎可以更容易地单独计算特定关键字。考虑到我不需要单独计算每个关键字,你认为我这样做有缺点吗?开始只包含关键字的映射,每个关键字的值为0。调用Map.get获取该值,如果它返回一个非空值,则将其递增并重新存储。如果它是空的,那么就没有什么可做的了,因为它不是一个关键字。Hristo,在我浏览你所有的代码之前,是的,家庭作业已经完成了。另外,至于为什么我有50多个关键词,作业中规定我们还应该包括3个保留字;false、null和true。。我忘了提了。谢谢你的来信。。我要通读一遍,看看你现在做事的方式。我非常感激看到有人会用更多的编程经验来完成任务。明白了。我会把它们添加到我的列表中。2.我没有“更多的编程经验”。我还是个大学生:)3。祝你好运让我知道你的想法,如果你有问题。与此同时,我要去睡一会儿。br.close属于finally语句。与br(fr(file))相比,java.util.Scanner的使用似乎要简单得多。注释是噪音(
FileNotFoundException异常){//找不到文件。
//无法读取行
。如果(a==0){/*empty*/},则不使用
,否则…
只需写入
if(a!=0){…
。谢谢你的建议。关于
扫描仪
,根据我的经验,它比使用
文件阅读器
缓冲阅读器
if (theKeywordCount.containsKey(sLine)) {
    occurrences++;
}