本节介绍一个计算 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<string> 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 行)。

您可以重写程序以使用linkedhashset、treeset、arraylist或linkedlist来存储关键字。然而,使用 hashset 对于这个程序来说是最有效的。

    以上就是案例研究:计算关键词的详细内容,更多请关注php中文网其它相关文章!