package set;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Exercise21_10 {
public static void main(String[] args) throws IOException {
System.out.print("Enter a file: ");
File file = new File(new Scanner(System.in).nextLine());
if (!file.exists())
System.out.println("File " + file + " does not exist");
else if (!file.isFile())
System.out.println("Not a file");
else {
int count = 0;
Set<Map.Entry<String, Integer>> entrySet = countKeywords(file).entrySet();
for (Map.Entry<String, Integer> entry: entrySet) {
count += entry.getValue();
System.out.println(String.format("%-10s%10d", entry.getKey(), entry.getValue()));
}
System.out.println("count = " + count);
}
}
public static Map<String, Integer> countKeywords(File file) throws IOException {
Set<String> keywordSet = getKeywordSet();
Map<String, Integer> map = new TreeMap<>();
try(Scanner input = new Scanner(file)) {
while (input.hasNext()) {
String word = input.next();
if (word.contains("\"") && !word.matches(".*(\").*")) {
word = input.next();
while (input.hasNext() && !word.contains("\""))
word = input.next();
word = input.next();
}
if (word.contains("/*") && !word.matches("\".*/\\*\".*")) {
word = input.next();
while (input.hasNext() && !word.contains("*/"))
word = input.next();
word = input.next();
}
if (word.contains("//")) {
input.nextLine();
if (input.hasNext())
word = input.next();
}
if (keywordSet.contains(word)) {
if (!map.containsKey(word))
map.put(word, 1);
else
map.put(word, map.get(word)+1);
} else {
for (String s: keywordSet) {
for (String s1 : word.split("[ ().]"))
if (s1.matches(s)) {
if (!map.containsKey(s))
map.put(s, 1);
else
map.put(word, map.get(s) + 1);
}
}
}
}
}
return map;
}
/** 返回关键字集合 */
public static Set<String> getKeywordSet() {
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));
return keywordSet;
}
}