作者 段喜龙
单位 南昌航空大学
题目描述
编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。说明如下:
- java中共有53个关键字(自行百度)
- 从键盘输入一段源码,统计这段源码中出现的关键字的数量
- 注释中出现的关键字不用统计
- 字符串中出现的关键字不用统计
- 统计出的关键字及数量按照关键字升序进行排序输出
-
未输入源码则认为输入非法
输入格式
-
输入Java源码字符串,可以一行或多行,以
exit
行作为结束标志
输出格式
- 当未输入源码时,程序输出
Wrong Format
- 当没有统计数据时,输出为空
- 当有统计数据时,关键字按照升序排列,每行输出一个关键字及数量,格式为
数量\t关键字
输入样例
//Test public method
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
exit
输出样例
1 float
3 if
2 int
2 new
2 public
3 this
2 throw
题解
import java.util.*;
class Main{
public static void main(String[] args){
String[] keywords = new String[]{
"boolean","byte","char","double","float","int","long","short","void","class","interface","enum",
"if","else","switch","case","default","while","do","for","break","continue","return",
"private","protected","public","abstract","final","static","synchronized","extends","implements",
"new","this","super","instanceof","try","catch","finally","throw","throws","package","import",
"native","strictfp","transient","volatile","assert","true","false","null","const","goto"
};
Arrays.sort(keywords);
Scanner scan = new Scanner(System.in);
HashMap<String,Integer> hmap = new HashMap<>();
for(String each : keywords){
hmap.put(each,0);
}
String text = "";
while(true){
String line = scan.nextLine();
if(line.equals("exit")){
break;
}
text = text + line + '\n';
}
scan.close();
if(text.equals("")){
System.out.println("Wrong Format");
return;
}
String[] words = text.split("\"[^\"]*\"|//.*|/\\*(.|\\n)*?\\*/|[^\\w=]");
//这里必须将=不作为分隔符才能过pta,原因不详
for(String word : words){
for(String keyword : keywords){
if(word.equals(keyword)){
hmap.put(keyword,hmap.get(keyword) + 1);
break;
}
}
}
for(String keyword : keywords){
if(hmap.get(keyword) > 0){
System.out.format(hmap.get(keyword) + "\t" + keyword + "\n");
}
}
}
}