Home  >  Article  >  Java  >  Case Study: Counting Keywords

Case Study: Counting Keywords

王林
王林Original
2024-07-18 08:05:39830browse

Case Study: Counting Keywords

This section presents an application that counts the number of the keywords in a Java source file. For each word in a Java source file, we need to determine whether the word is a keyword. To handle this efficiently, store all the keywords in a HashSet and use the contains method to test if a word is in the keyword set. The code below gives this program.

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;
    }

}

Enter a Java source file: c:Welcome.java
The number of keywords in c:Welcome.java is 5

Enter a Java source file: c:TTT.java
File c:TTT.java does not exist

The program prompts the user to enter a Java source filename (line 9) and reads the filename (line 10). If the file exists, the countKeywords method is invoked to count the keywords in the file (line 15).

The countKeywords method creates an array of strings for the keywords (lines 26) and creates a hash set from this array (lines 28). It then reads each word from the file and tests if the word is in the set (line 35). If so, the program increases the count by 1 (line 36).

You may rewrite the program to use a LinkedHashSet, TreeSet, ArrayList, or LinkedList to store the keywords. However, using a HashSet is the most efficient for this program.

The above is the detailed content of Case Study: Counting Keywords. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Nested loopsNext article:Nested loops