我正在开发一个工具来分析并提供有关其他人的源代码的一些统计信息,该工具将能够识别代码中的许多内容!现在我被困在计算代码的评论数量,我目前的代码是:
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
Run Code Online (Sandbox Code Playgroud)
要检查代码,我使用的是测试文件.但是代码在两个文件中都给出了错误的结果,例如; 我在以下文件中得到三个
Yes
//comment
yes
yes
/*
if
random
test
test
*/
Run Code Online (Sandbox Code Playgroud)
虽然答案应该是两条评论!
在下面的文件中,它显示我有五条评论,而我实际上还有两条评论
Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/
Run Code Online (Sandbox Code Playgroud)
整个方法都存在缺陷.您需要正确解析源文件,至少需要正确跟踪引号和嵌套"/*".请注意,任何注释字符组合都可以出现在以下语句中:
System.out.println("// this is *not* a line comment");
String s = "*/ this is not the end of a block comment";
Run Code Online (Sandbox Code Playgroud)
等等.然后是在解释文件之前处理字符转义序列的奇怪行为:
\u002F* this is a valid comment */
Run Code Online (Sandbox Code Playgroud)
它不是那容易确定哪些是注释,没有什么:)我强烈建议你找对Java源代码的开源解析器的解决方案.