请为“统计Java程序中关键词的出现次数”提供一些测试源码
时间: 2024-01-24 19:16:53 浏览: 80
以下是一个Java程序的示例代码,用于统计关键词的出现次数:
```java
import java.util.*;
public class KeywordCounter {
public static void main(String[] args) {
// Java keywords
String[] keywords = {"abstract", "assert", "boolean", "break", "byte",
"case", "catch", "char", "class", "const", "continue", "default",
"do", "double", "else", "enum", "extends", "final", "finally",
"float", "for", "if", "goto", "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"};
// read Java source code from file or input stream
String sourceCode = "public class HelloWorld {\n" +
" public static void main(String[] args) {\n" +
" System.out.println(\"Hello, World!\");\n" +
" }\n" +
"}";
// count keywords
Map<String, Integer> keywordCount = new HashMap<>();
for (String keyword : keywords) {
keywordCount.put(keyword, 0);
}
String[] tokens = sourceCode.split("\\W+");
for (String token : tokens) {
if (Arrays.asList(keywords).contains(token)) {
keywordCount.put(token, keywordCount.get(token) + 1);
}
}
// print result
for (String keyword : keywords) {
System.out.println(keyword + ": " + keywordCount.get(keyword));
}
}
}
```
你可以根据自己的需要修改 `sourceCode` 变量的值,来测试不同的 Java 代码。
阅读全文