编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。说明如下: Java中共有53个关键字(自行百度) 从键盘输入一段源码,统计这段源码中出现的关键字的数量 注释中出现的关键字不用统计 字符串中出现的关键字不用统计 统计出的关键字及数量按照关键字升序进行排序输出 未输入源码则认为输入非法 输入格式: 输入Java源码字符串,可以一行或多行,以exit行作为结束标志 输出格式: 当未输入源码时,程序输出Wrong Format 当没有统计数据时,输出为空 当有统计数据时,关键字按照升序排列,每行输出一个关键字及数量,格式为数量\t关键字
时间: 2024-03-02 20:53:19 浏览: 140
好的,我可以帮你编写这个程序。以下是程序代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Set<String> keywords = new TreeSet<>(Arrays.asList("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> countMap = new TreeMap<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("exit")) {
break;
}
line = line.trim();
// 判断是否为注释行
if (line.startsWith("//")) {
continue;
}
if (line.startsWith("/*") && !line.endsWith("*/")) {
while (scanner.hasNextLine()) {
line = scanner.nextLine().trim();
if (line.endsWith("*/")) {
break;
}
}
continue;
}
if (line.startsWith("/*") && line.endsWith("*/")) {
continue;
}
// 提取关键字
String[] words = line.split("\\W+");
for (String word : words) {
if (keywords.contains(word)) {
countMap.put(word, countMap.getOrDefault(word, 0) + 1);
}
}
}
if (countMap.isEmpty()) {
System.out.println("");
} else {
countMap.forEach((key, value) -> System.out.println(value + "\t" + key));
}
}
}
```
这个程序使用了 `Scanner` 类从标准输入读取输入的源码,然后使用正则表达式提取出关键字,再统计关键字出现的次数,并按照关键字升序输出统计结果。
请注意,本程序只支持统计单个 Java 源文件中的关键字,不支持统计多个源文件中的关键字。如果需要统计多个源文件中的关键字,可以将程序改为读取目录中的所有 Java 源文件,并将每个文件的关键字出现次数累加到总的关键字出现次数中。
阅读全文
相关推荐













