编写程序统计一个输入的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
// 双指针算法+HashMap+TreeMap+正则表达式
import java.util.*;
public class Main {
public static boolean check( char x) {
if((x>='a'&&x<='z') || (x>='A'&&x<='Z')) return true;
else return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<String,Integer> map = new HashMap<>();
TreeMap<String,Integer> res = new TreeMap<>();
String str[] = {"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","int","interface","instanceof","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while","goto","const","true","false","null"};
for(int i=0; i<53; i++) map.put( str[i], 0);
boolean F = true;
while(sc.hasNext()) {
String s1 = sc.nextLine();
StringBuffer s = new StringBuffer();
if(s1.equals("exit")) break;
F = false;
s.append(s1.replaceAll("\".*\"","").replaceAll("//.*","")); //运用正则表达式去除//注释的和双引号里的内容
if(s.indexOf("/*")!=-1) { //删除/* */ 注释的
if(s.indexOf("*/")!=-1) s.delete( s.indexOf("/*"), s.indexOf("*/")+2); // /* */注释没有跨行
else { // /* */跨行
s.delete( s.indexOf("/*"), s.length());
while(sc.hasNext()) { //一直输入知道出现 */
String sr = sc.nextLine();
if(sr.indexOf("*/")!=-1) {
s.append( sr.substring(sr.indexOf("*/")+2));
break;
}
}
}
}
String sr = s.toString();
sr = sr.replace("=", "a"); //测试点2
int l = sr.length();
for(int i=0; i<l; i++) { //运用双指针扫描,把每个词提取出来
while(i<l && check( sr.charAt(i) ) == false) i++;
int j = i;
while(j<l && check( sr.charAt(j) ) == true) j++;
if(i < l) {
String r = sr.substring( i, j); //把扫描出来的单词提前出来
if(map.containsKey(r) == true ) { //判断是否是关键词
if(res.containsKey(r) == false) res.put( r, 1);
else res.replace( r, (res.get(r)+1));
}
}
i = j;
}
}
if( F ) System.out.println("Wrong Format");
else if(res.size()!=0){
for(String i: res.keySet())
System.out.println(res.get(i) + "\t" + i);
}
}
}