Java代码实现,输入一段代码,找出里面的关键字并分别计数
时间: 2023-07-10 13:09:48 浏览: 82
以下是Java代码实现,可以输入一段代码,找出里面的关键字并分别计数:
```java
import java.util.HashMap;
import java.util.Scanner;
public class KeywordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一段代码:");
String code = scanner.nextLine();
scanner.close();
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"};
HashMap<String, Integer> keywordCount = new HashMap<>();
for (String keyword : keywords) {
keywordCount.put(keyword, 0);
}
String[] words = code.split("\\W+");
for (String word : words) {
if (keywordCount.containsKey(word)) {
keywordCount.put(word, keywordCount.get(word) + 1);
}
}
System.out.println("关键字统计结果如下:");
for (String keyword : keywordCount.keySet()) {
int count = keywordCount.get(keyword);
if (count > 0) {
System.out.println(keyword + ": " + count);
}
}
}
}
```
使用HashMap存储每个关键字出现的次数,然后遍历代码中的每个单词,如果是关键字则对应的计数器加1。最后输出统计结果。
阅读全文