1+ /*********************************************************************************
2+ * (Count the keywords in Java source code) Revise the program in Listing 21.7. *
3+ * If a keyword is in a comment or in a string, don’t count it. Pass the Java *
4+ * file name from the command line. Assume that the Java source code is correct *
5+ * and line comments and paragraph comments do not overlap. *
6+ *********************************************************************************/
7+ import java .util .*;
8+ import java .io .*;
9+
10+ public class Exercise_21_03 {
11+ public static void main (String []args )throws Exception {
12+ // Check command line length
13+ if (args .length !=1 ) {
14+ System .out .println ("Usage: java sourceFile" );
15+ System .exit (1 );
16+ }
17+
18+ // Check if file exists and display keyword count
19+ File file =new File (args [0 ]);
20+ if (file .exists ()) {
21+ System .out .println ("The number of keywords in " +args [0 ]
22+ +" is " +countKeywords (file ));
23+ }
24+ else {
25+ System .out .println ("File " +args [0 ] +" does not exist" );
26+ }
27+ }
28+
29+ /** Method returns the keyword count */
30+ public static int countKeywords (File file )throws Exception {
31+ // Array of all Java Keywords + ture, false and null
32+ String []keywordString = {"abstract" ,"assert" ,"boolean" ,
33+ "break" ,"byte" ,"case" ,"catch" ,"char" ,"class" ,"const" ,
34+ "continue" ,"default" ,"do" ,"double" ,"else" ,"enum" ,
35+ "extends" ,"for" ,"final" ,"finally" ,"float" ,"goto" ,
36+ "if" ,"implements" ,"import" ,"instanceof" ,"int" ,
37+ "interface" ,"long" ,"native" ,"new" ,"package" ,"private" ,
38+ "protected" ,"public" ,"return" ,"short" ,"static" ,
39+ "strictfp" ,"super" ,"switch" ,"synchronized" ,"this" ,
40+ "throw" ,"throws" ,"transient" ,"try" ,"void" ,"volatile" ,
41+ "while" ,"true" ,"false" ,"null" };
42+
43+ Set <String >keywordSet =
44+ new HashSet <>(Arrays .asList (keywordString ));
45+ int count =0 ;
46+
47+ Scanner input =new Scanner (file );
48+
49+ while (input .hasNext ()) {
50+ String word =input .next ();
51+ if (word .equals ("//" )) {// Don't count comments
52+ input .nextLine ();
53+ }
54+ else if (word .contains ("\" " )) {// Don't count string
55+ String nextWord ;
56+ do {
57+ nextWord =input .next ();
58+ }while (!nextWord .contains ("\" " ));
59+ }
60+ else if (word .contains ("/*" )) {// Don't count block comments
61+ String nextWord ;
62+ do {
63+ nextWord =input .next ();
64+ }while (!nextWord .contains ("*/" ));
65+ }
66+ else if (keywordSet .contains (word ))
67+ count ++;
68+ }
69+
70+ return count ;
71+ }
72+ }