编写程序统计一个输入的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 map = new HashMap<>();
TreeMap 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(" 注释的
if(s.indexOf("*/")!=-1) s.delete( s.indexOf("")+2); // 注释没有跨行
else { // 跨行
s.delete( s.indexOf("
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



