The following program counts how many times specific Java words appear in the program itself.
import java.util.*;
public class Program {
public static void main (String[] args) throws Exception {
String[] keywords = {"import", "public", "for", "if", "else",
"class", "static", "throws", "while", "new"};
int[] index = new int[keywords.length];
BufferedReader bf = new BufferedReader(new FileReader ("Program.java"));
String text = "", line;
while ((line = bf.readLine()) != null) {
text += line + "\n";
}
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens()) {
String word = st.nextToken();
for (int i = 0; i < keywords.length; ++i) {
if (word.equals(keywords[i])) {
index[i]++;
}
} // end for
} // end while
for (int i = 0; i < keywords.length; ++i) {
System.out.println(keywords[i] + ": " + index[i]);
} // end for
} // end main
} // end class
The result (what you see in the console):
import: 2
public: 2
for: 4
if: 1
else: 0
class: 2
static: 1
throws: 1
while: 3
new: 3