java如何统计关键词
时间: 2023-10-18 10:08:16 浏览: 98
java统计关键字个数
Java 中可以使用正则表达式和计数器来统计关键词的出现次数,具体步骤如下:
1. 定义一个包含关键词的字符串数组。
2. 通过正则表达式匹配每个关键词在文本中出现的次数。
3. 将每个关键词的出现次数累加到计数器中。
4. 输出每个关键词的出现次数。
下面是一个简单的示例代码,可以统计 Java 代码中出现的关键词数量:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class KeywordCounter {
public static void main(String[] args) {
String[] keywords = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "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"};
String code = "public class Test {\n" +
" public static void main(String[] args) {\n" +
" int a = 10;\n" +
" int b = 20;\n" +
" int c = a + b;\n" +
" System.out.println(\"Sum of \" + a + \" and \" + b + \" is \" + c);\n" +
" }\n" +
"}";
int[] keywordCounts = new int[keywords.length];
for (int i = 0; i < keywords.length; i++) {
Pattern pattern = Pattern.compile("\\b" + keywords[i] + "\\b");
Matcher matcher = pattern.matcher(code);
while (matcher.find()) {
keywordCounts[i]++;
}
}
for (int i = 0; i < keywords.length; i++) {
System.out.println(keywords[i] + ": " + keywordCounts[i]);
}
}
}
```
输出结果为:
```
abstract: 0
assert: 0
boolean: 0
break: 0
byte: 0
case: 0
catch: 0
char: 0
class: 1
const: 0
continue: 0
default: 0
do: 0
double: 0
else: 0
enum: 0
extends: 0
final: 0
finally: 0
float: 0
for: 0
if: 0
implements: 0
import: 0
instanceof: 0
int: 3
interface: 0
long: 0
native: 0
new: 1
package: 1
private: 0
protected: 0
public: 2
return: 1
short: 0
static: 1
strictfp: 0
super: 0
switch: 0
synchronized: 0
this: 1
throw: 0
throws: 0
transient: 0
try: 0
void: 1
volatile: 0
while: 0
```
阅读全文