现在有这样的代码可以算出代码中有多少行.
Private int sumLine = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream(f)));
while (br.readLine() != null) {
sumLine++;
}
然后算注释行的时候有几种情况,比较简单的就是
br.readLine().startsWith(“/*”) && br.readLine().startsWith(“/**”)&&(startsWith(“//”) 这几种吧。
但是还有一种比较困难,比如说
/** ssss
ssss
ss
**/
这样是4行注释行,怎么用语句来判断这种情况呢?PS:没分了,但是希望好心人帮帮我,以后有分了会回来还的!
Private int sumLine = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream(f)));
while (br.readLine() != null) {
sumLine++;
}
然后算注释行的时候有几种情况,比较简单的就是
br.readLine().startsWith(“/*”) && br.readLine().startsWith(“/**”)&&(startsWith(“//”) 这几种吧。
但是还有一种比较困难,比如说
/** ssss
ssss
ss
**/
这样是4行注释行,怎么用语句来判断这种情况呢?PS:没分了,但是希望好心人帮帮我,以后有分了会回来还的!
其间还要排除 /* illustration */ 把这样注释写在一行里面的变态写法。不能使用 startWith(),要用 indexOf(),因为前面有可能有空格或者是 Tab。对于 // 来说,独占一行的当然算一行,那放在代码行尾的那怎么算?
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;public class Comment { public static void main(String[] args) {
Comment comment = new Comment();
int count = comment.countCommentLine("Test.java");
System.out.println(count);
}
public int countCommentLine(String filename) {
if(filename.toLowerCase().lastIndexOf(".java") <= 0) {
throw new IllegalJavaFile(filename);
}
int count = 0;
List<String> list = readFile(filename);
boolean isMultiLineComment = false;
for(String str : list) {
// 当为多行注释时,直接将计算注释行
if(isMultiLineComment) {
count++;
// 直到碰到 */ 为止,当然 */ 这一行也算注释
if(str.indexOf("*/") >= 0) {
isMultiLineComment = false;
}
}
// 为 // 直接计数
if(str.indexOf("//") >= 0) {
count++;
}
// 当碰到 /* 时,开始计数
if(str.indexOf("/*") >= 0) {
count++;
// 并且在该行中没 */ 时,可以看作是多行注释的开始
if(str.indexOf("*/") < 0) {
isMultiLineComment = true;
}
}
}
return count;
}
private List<String> readFile(String filename) {
List<String> list = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String str = "";
while((str = br.readLine()) != null) {
str = str.trim();
// 忽略空行
if(str.length() > 0) {
list.add(str);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
}class IllegalJavaFile extends RuntimeException {
private static final long serialVersionUID = 1L;
public IllegalJavaFile(String filename){
super("\"" + filename + "\", the file is not a java file.");
}
}
测试文件 Test.java,有 13 行注释。// Test File
package color;/**
* My firat Java program: Hello World
* @author bao110908
*/
public class Test{ /*
main method
method of automatic startup
*/
/* abnormal comment 1 */
/** abnormal comment 2 **/
// normal comment
public static void main(String[] args) {
System.out.println("Hello World"); // print 'Hello World'
}
}