【问题描述】
一个好的程序要有一定比例的注释。编写一个程序统计一个C源文件中注释所占的百分比。百分比计算公式为:程序注释中字符总数(/*
和*/
除外的所有字符)除以程序文件中总字符数(程序文件中的所有字符)。
注:只简单考虑/*...*/
的注释,而且要考虑注释跨行的情况,不要考虑其它复杂情况。
文件中只计算字符之间的空格,字符之外的空格不计入总空格数
【输入形式】
从当前目录下的filein.c源程序文件获得输入。
【输出形式】
向控制台输出注释所占百分比,百分数无小数(小数部分直接截掉,不要四舍五入),后跟百分号%。
【样例输入】
假设filein.c的内容为:
void main()
{
FILE * in;
/*Open the file*/
if((in=fopen("in.txt","r"))==NULL)
{
printf("Can’t open in.txt!");
return;
}
/*Close the file,
and return.*/
fclose(in);
}
【样例输出】
22%
【样例说明】
filein.c文件的总字符数为179,注释中的字符数为41,则注释所占百分比为22%。
【样例代码】
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class AnnotationScale {
static BufferedReader br;
public static void main(String[] args) throws UnsupportedEncodingException {
PrintStream ps = new PrintStream(System.out, true, "UTF-8");
File f = new File("filein.c");
StringBuffer content = new StringBuffer();
try {
FileReader fr = new FileReader(f);
br = new BufferedReader(fr);
String line;
int left = 0;//左花括号出现的次数
int right = 0;//右花括号出现的次数
try {
line = br.readLine(); //读取第一行
while (line != null) {
if (line.indexOf("{") != -1) {
left++;
}
if (line.indexOf("}") != -1) {
right++;
}
if (left != right) { //当左右的花括号不匹配时候,表示在花括号内,那么前面这一行的字符串前面应该空两格
line = " " + line.trim();
} else {
line = line.trim();
}
content.append(line);
line = br.readLine();
}
br.close();
fr.close();
} catch (IOException e) {
ps.println("文件读取失败");
}
} catch (FileNotFoundException e) {
ps.println("文件不存在");
}
StringBuffer allContent = new StringBuffer(content);// 定义变量保留原字符总串
StringBuffer annotationContent = new StringBuffer();
while (content.indexOf("/*") != -1 && content.indexOf("*/") != -1) {
annotationContent.append(content.substring(content.indexOf("/*") + 2, content.indexOf("*/")));
content.delete(content.indexOf("/*"), content.indexOf("*/") + 2);// 加好就删掉出这个注释
}
// ps.println(allContent);
// ps.println("总字符长度:" + allContent.length());// 总字符长度
// ps.println(annotationContent);
// ps.println("注释的字符串长度:" + annotationContent.length());// 注释的字符串串在一起的长度
int scale = annotationContent.length() * 100 / allContent.length();// 字符占的百分比
// ps.println("注释比率:" + scale + "%");
ps.println(scale + "%");
}
}