1

すべての Java キーワードを HashSet に追加するという宿題がありました。次に、.java ファイルを読み込み、キーワードが .java ファイルに出現した回数を数えます。

私が取ったルートは次のとおりです。すべてのキーワードを含む String[] 配列を作成しました。HashSet を作成し、Collections.addAll を使用して配列を HashSet に追加しました。次に、テキスト ファイルを繰り返し処理しながら、HashSet.contains(currentWordFromFile); でチェックします。

これを行うために HashTable を使用することを誰かが推奨しました。次に、TreeSet を使用した同様の例を見ました。私はただ興味がありました..これを行うための推奨される方法は何ですか?

(完全なコードはこちら: http://pastebin.com/GdDmCWj0 )

4

2 に答える 2

2

Map<String, Integer>文字列が単語で、整数が単語が表示された回数であるa を試してください。

この利点の 1 つは、ファイルを 2 回処理する必要がないことです。

于 2011-04-27T05:22:15.260 に答える
1

あなたは「宿題があった」と言ったので、これで終わったと思います。

私はそれを少し違う方法で行います。Stringまず、配列内のいくつかのキーワードが間違っていたと思います。WikipediaOracleによると、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);
    }
}

ファイルのキーワードに遭遇するたびに、まずそれがマップにあるかどうかを確認します。そうでない場合は、有効なキーワードではありません。そうである場合は、キーワードが関連付けられている値を更新します。つまり、Integerこのキーワードをもう一度見たので、関連付けられた値を 1 増やします。

または、最後の for ループを取り除き、実行中のカウントを保持することもできます。代わりに...

if (theKeywordCount.containsKey(sLine)) {
    occurrences++;
}

...そして最後にカウンターを出力します。

これが最も効率的な方法かどうかはわかりませんが、手堅いスタートだと思います。

ご不明な点がございましたら、お知らせください。これが役立つことを願っています。
フリスト

于 2011-04-27T06:12:47.383 に答える