编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数未输入源码则认为输入非法, 当未输入源码时,程序输出Wrong Format 当没有统计数据时,输出为空 当有统计数据时,关键字按照升序排列,
时间: 2024-02-28 08:56:26 浏览: 64
培训机构系统全套源码(微信小程序 后台Java).zip
以下是代码实现:
```java
import java.util.*;
public class KeywordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入Java源码:");
String sourceCode = scanner.nextLine().trim();
if (sourceCode.isEmpty()) {
System.out.println("Wrong Format");
return;
}
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"
};
Map<String, Integer> keywordCountMap = new TreeMap<>();
String[] lines = sourceCode.split("\n");
for (String line : lines) {
line = line.trim();
if (!line.isEmpty() && !line.startsWith("//") && !line.startsWith("/*")) {
String[] words = line.split("[\\s\\p{Punct}&&[^$_]]+");
for (String word : words) {
if (Arrays.asList(keywords).contains(word)) {
keywordCountMap.put(word, keywordCountMap.getOrDefault(word, 0) + 1);
}
}
}
}
if (keywordCountMap.isEmpty()) {
System.out.println("没有统计数据");
} else {
System.out.println("关键字\t数量");
for (String keyword : keywordCountMap.keySet()) {
System.out.println(keywordCountMap.get(keyword) + "\t" + keyword);
}
}
}
}
```
这个程序使用了一个字符串数组 `keywords` 来存储 Java 中的关键字,使用了一个 Map `keywordCountMap` 来存储每个关键字出现的次数。程序将输入的源码按行分割,对每一行进行分词,统计出现的关键字的数量。最后按照关键字升序输出统计结果。
阅读全文