Question: Rewrite Listing 21.7 CountKeywords. java to read in a Java source code file and count the occurrence of each keyword in the file, but don?t
Rewrite Listing 21.7 CountKeywords. java to read in a Java source code file and count the occurrence of each keyword in the file, but don?t count the keyword if it is in a comment or in a string literal.
Listing

![public static void main(String[] args) throws Exception { Scanner input = new](https://dsd5zvtm8ll6.cloudfront.net/si.experts.images/questions/2022/11/636a73d56af0e_853636a73d55a4a0.jpg)
1 import java.util.*; 2 import java.io.*; 3 4 public class Countkeywords { public static void main(String[] args) throws Exception { Scanner input = new Scanner (System.in); System.out.print("Enter a Java source file: "); String filename = input.nextline(); 8 File file = new File(filename); if (file.exists()) { System.out.println("The number of keywords in " + filename is " + countkeywords(file)); 10 11 12 13 14 else { System.out.println("File " + filename + " does not exist"); 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public static int countkeywords (File file) throws Exception { // Array of al1 Java keywords + true, false and null String[] keywordString - {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "e "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"}; 'enum", 33 Set keywordSet = new HashSet (Arrays.asList(keywordString)); int count = 0; 34 35 36 Scanner input - new Scanner(file); 37 38 while (input.hasNext ()) { String word = input.next(); if (keywordSet.contains (word)) 39 40 41 42 count++; 43 44 45 return count; 46 47 } Enter a Java source file: c:\Welcome.java Jenter The number of keywords in c:\Welcome.java is 5 Enter a Java source file: c:\TTT.java -Enter File c:\TTT.java does not exist
Step by Step Solution
3.36 Rating (171 Votes )
There are 3 Steps involved in it
Program Plan Create a class called Count keywords Read a file name from the keyboard Check for existence of the file Define a method called Count keyw... View full answer
Get step-by-step solutions from verified subject matter experts
