Java代码实现输入一段代码,当输入exit停止,统计这段代码中的各个关键词个数,需要再创建一个方法除去代码中的注释部分
时间: 2024-02-12 13:07:19 浏览: 73
清除Java代码注释
好的,以下是 Java 实现代码:
```java
import java.util.HashMap;
import java.util.Scanner;
public class KeywordCounter {
// Java 关键词
private static final String[] KEYWORDS = new String[] {
"abstract", "assert", "boolean", "break", "byte", "case", "catch",
"char", "class", "const", "continue", "default", "do", "double",
"else", "enum", "extends", "final", "finally", "float", "for",
"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"
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder code = new StringBuilder();
String line;
while (!(line = scanner.nextLine()).equals("exit")) {
code.append(line).append('\n');
}
scanner.close();
// 计算关键词数量
HashMap<String, Integer> keywordCount = countKeywords(code.toString());
System.out.println("关键词数量统计结果:");
for (String keyword : keywordCount.keySet()) {
System.out.println(String.format("%-15s: %d", keyword, keywordCount.get(keyword)));
}
}
private static HashMap<String, Integer> countKeywords(String code) {
HashMap<String, Integer> keywordCount = new HashMap<>();
code = removeComments(code);
String[] words = code.split("\\W+"); // 以非单词字符为分隔符
for (String word : words) {
if (isKeyword(word)) {
keywordCount.put(word, keywordCount.getOrDefault(word, 0) + 1);
}
}
return keywordCount;
}
private static boolean isKeyword(String word) {
for (String keyword : KEYWORDS) {
if (keyword.equals(word)) {
return true;
}
}
return false;
}
private static String removeComments(String code) {
// 匹配单行注释和多行注释
code = code.replaceAll("//.*", "");
code = code.replaceAll("/\\*.*?\\*/", "");
return code;
}
}
```
该程序首先会循环读入用户输入的代码,直到用户输入 `exit`。然后,调用 `countKeywords` 方法统计代码中各个关键词的数量,并输出结果。
`countKeywords` 方法会先调用 `removeComments` 方法去除代码中的注释部分,然后使用正则表达式分割代码为单词,判断每个单词是否为 Java 关键词,最终统计出每个关键词的数量。
`removeComments` 方法使用正则表达式匹配单行注释和多行注释,并将其替换为空字符串。
注意:该程序只能处理不带语法错误的代码。
阅读全文