"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Case Study: Counting Keywords

Case Study: Counting Keywords

Published on 2024-07-31
Browse:493

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 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.

Release Statement This article is reproduced at: https://dev.to/paulike/case-study-counting-keywords-4kfa?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3