java统计Java程序中关键词的出现次数不统计字符和注释中的关键字,以exit作为标识符结束统计出的关键字及数量按照关键字升序进行排序输出 未输入源码则认为输入非法
时间: 2024-03-13 11:47:01 浏览: 76
java统计关键字个数
好的,我可以为您提供Java代码来完成这个任务。代码如下:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class KeywordCounter {
private static final String[] KEYWORDS = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "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"};
private static final Set<String> KEYWORDS_SET = new HashSet<>(Arrays.asList(KEYWORDS));
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入Java源代码文件路径:");
String filePath = scanner.nextLine();
Map<String, Integer> keywordCountMap = new TreeMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
boolean inString = false;
boolean inComment = false;
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("/*")) {
inComment = true;
}
if (inComment) {
if (line.endsWith("*/")) {
inComment = false;
}
continue;
}
if (line.startsWith("//")) {
continue;
}
if (line.endsWith("*/")) {
continue;
}
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"') {
inString = !inString;
continue;
}
if (inString) {
continue;
}
if (c == '/' && i + 1 < line.length() && line.charAt(i + 1) == '/') {
break;
}
if (c == '/' && i + 1 < line.length() && line.charAt(i + 1) == '*') {
inComment = true;
i++;
continue;
}
if (!Character.isJavaIdentifierPart(c)) {
continue;
}
StringBuilder sb = new StringBuilder();
sb.append(c);
int j = i + 1;
while (j < line.length() && Character.isJavaIdentifierPart(line.charAt(j))) {
sb.append(line.charAt(j));
j++;
}
String word = sb.toString();
if (KEYWORDS_SET.contains(word)) {
int count = keywordCountMap.getOrDefault(word, 0);
keywordCountMap.put(word, count + 1);
}
i = j - 1;
}
}
} catch (IOException e) {
System.out.println("读取文件失败:" + e.getMessage());
return;
}
if (keywordCountMap.isEmpty()) {
System.out.println("未找到任何关键字!");
return;
}
System.out.println("关键字\t\t出现次数");
System.out.println("==========================");
for (Map.Entry<String, Integer> entry : keywordCountMap.entrySet()) {
System.out.printf("%-15s%d\n", entry.getKey(), entry.getValue());
}
}
}
```
当您运行此代码时,程序将提示您输入Java源代码文件的路径。程序将扫描文件并计算出现的关键字的数量,然后按关键字升序输出。
请注意,此代码仅计算源代码中的关键字,不包括字符常量和注释中的关键字。如果没有提供有效的源代码文件路径,则程序将退出。
阅读全文