package set;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Exercise21_03 {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Invalid length");
} else {
File file = new File(args[0]);
if (!file.exists())
System.out.println("File " + file + "does not exist");
else
System.out.println("The number of keywords in " + file + " is " + countKeywords(file));
}
}
/** 统计关键字次数 false boolean assert */
public static int countKeywords(File file) throws IOException {
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; //次数
try(Scanner input = new Scanner(file)) {
while (input.hasNext()) { //读入文本
String word = input.next(); //false boolean assert
//字符串包含引号且不匹配转义字符引号
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)) {
count++;
} else {
for (String s: keyWordString) //检查字符串中的单词是否匹配关键字
for (String s1: word.split("[ ().]"))
if (s1.matches(s)) {
count++;
}
}
}
}
return count;
}
}