”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 案例研究:计算关键词

案例研究:计算关键词

发布于2024-07-31
浏览:355

Case Study: Counting Keywords

本节介绍一个计算 Java 源文件中关键字数量的应用程序。对于Java源文件中的每个单词,我们需要判断该单词是否是关键字。为了有效地处理这个问题,请将所有关键字存储在 HashSet 中,并使用 contains 方法来测试某个单词是否在关键字集中。下面的代码给出了这个程序。

package demo;
import java.util.*;
import java.io.*;

public class CountKeywords {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a Java source file: ");
        String filename = input.nextLine();

        File file = new File(filename);
        if(file.exists()) {
            try {
                System.out.println("The number of keywords in "   filename   " is "   countKeywords(file));
            } catch (Exception e) {
                System.out.println("An error occurred while counting keywords: "   e.getMessage());
            }
        } else {
            System.out.println("File "   filename   " does not exist");
        }
    }

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

        Set keywordSet = new HashSet(Arrays.asList(keywordString));
        int count = 0;

        Scanner input = new Scanner(file);

        while(input.hasNext()) {
            String word = input.next();
            if(keywordSet.contains(word))
                count  ;
        }

        return count;
    }

}

输入Java源文件:c:\Welcome.java
c:\Welcome.java中的关键字数量为5

输入Java源文件:c:\TTT.java
文件 c:\TTT.java 不存在

程序提示用户输入 Java 源文件名(第 9 行)并读取文件名(第 10 行)。如果文件存在,则调用 countKeywords 方法统计文件中的关键字(第 15 行)。

countKeywords 方法为关键字创建一个字符串数组(第 26 行),并根据该数组创建一个哈希集(第 28 行)。然后它从文件中读取每个单词并测试该单词是否在集合中(第 35 行)。如果是,程序将计数加 1(第 36 行)。

您可以重写程序以使用LinkedHashSetTreeSetArrayListLinkedList来存储关键字。然而,使用 HashSet 对于这个程序来说是最有效的。

版本声明 本文转载于:https://dev.to/paulike/case-study-counting-keywords-4kfa?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3