编写一段java代码并使用treeMap使其能够计算输入的一段规范的源码所含有的关键词及数量
时间: 2024-03-14 19:43:42 浏览: 115
好的,我可以帮你完成这个任务。以下是使用TreeMap计算输入源码中关键词及数量的Java代码示例:
```java
import java.util.Scanner;
import java.util.TreeMap;
public class KeywordCounter {
public static void main(String[] args) {
// 定义TreeMap存储关键词及其数量
TreeMap<String, Integer> keywords = new TreeMap<>();
// 获取用户输入的源码
Scanner scanner = new Scanner(System.in);
System.out.println("请输入源码:");
String sourceCode = scanner.nextLine();
// 定义关键词数组
String[] keywordArr = {"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"};
// 遍历关键词数组,计算关键词数量
for (String keyword : keywordArr) {
int count = countKeyword(sourceCode, keyword);
if (count > 0) {
keywords.put(keyword, count);
}
}
// 输出关键词及其数量
System.out.println("关键词及其数量:");
for (String keyword : keywords.keySet()) {
System.out.println(keyword + ":" + keywords.get(keyword));
}
}
// 计算指定关键词在源码中出现的次数
private static int countKeyword(String sourceCode, String keyword) {
int count = 0;
int index = sourceCode.indexOf(keyword);
while (index != -1) {
count++;
index = sourceCode.indexOf(keyword, index + keyword.length());
}
return count;
}
}
```
这段代码中,我们首先定义了一个TreeMap用于存储关键词及其数量。然后通过Scanner获取用户输入的源码,并定义了一个关键词数组用于遍历计算关键词数量。接着,我们通过countKeyword方法统计每个关键词在源码中出现的次数,并将关键词及其数量放入TreeMap中。最后,我们遍历输出关键词及其数量。
注意:这段代码只能计算Java源码中的关键词,如果需要计算其他语言的关键词,需要修改关键词数组。
阅读全文