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 …


This content originally appeared on DEV Community and was authored by Paul Ngugi

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.


This content originally appeared on DEV Community and was authored by Paul Ngugi


Print Share Comment Cite Upload Translate Updates
APA

Paul Ngugi | Sciencx (2024-07-13T14:35:39+00:00) Case Study: Counting Keywords. Retrieved from https://www.scien.cx/2024/07/13/case-study-counting-keywords/

MLA
" » Case Study: Counting Keywords." Paul Ngugi | Sciencx - Saturday July 13, 2024, https://www.scien.cx/2024/07/13/case-study-counting-keywords/
HARVARD
Paul Ngugi | Sciencx Saturday July 13, 2024 » Case Study: Counting Keywords., viewed ,<https://www.scien.cx/2024/07/13/case-study-counting-keywords/>
VANCOUVER
Paul Ngugi | Sciencx - » Case Study: Counting Keywords. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/13/case-study-counting-keywords/
CHICAGO
" » Case Study: Counting Keywords." Paul Ngugi | Sciencx - Accessed . https://www.scien.cx/2024/07/13/case-study-counting-keywords/
IEEE
" » Case Study: Counting Keywords." Paul Ngugi | Sciencx [Online]. Available: https://www.scien.cx/2024/07/13/case-study-counting-keywords/. [Accessed: ]
rf:citation
» Case Study: Counting Keywords | Paul Ngugi | Sciencx | https://www.scien.cx/2024/07/13/case-study-counting-keywords/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.