规定:一行上既有代码又有注释算代码行数(例如:int a = 1; //注释);
Java源代码文件(要统计的源代码文件)
package cn.edu.ccit.fwh;
public class Test {
public static void main(String[] args) {
// 单行注释
int a=1;
System.out.println(a);
/*注释*/
/*
* 这是多行注释
*
*/
// 321
/*爱就像蓝天白云 晴风万里 忽然暴风雨*/
/*
* hahahahahahahahahha
*/
/**
* hahahahahahhahahah
*/
}
}
统计代码
package cn.edu.ccit.fwh;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
public class First {
public static void main(String[] args) throws Exception {
Reader reader=new FileReader(new File("src/cn/edu/ccit/fwh/Test.java"));
BufferedReader in=new BufferedReader(reader);
String line=null;
int countAnnotation=0; //注释
int countCodeLine=0; //代码
int countBlankLine=0; //空行
int countTotalLine=0; //总数
boolean flag=false;
while((line=in.readLine())!=null){
line=line.trim();
if(line.startsWith("//")){
countAnnotation++;
}else if(line.startsWith("/*")&&line.endsWith("*/")){
countAnnotation++;
}else if(line.startsWith("/*")&&!line.endsWith("*/")||flag){
flag=true;
countAnnotation++;
if(line.endsWith("*/")){
flag=false;
}
}else if(line.isEmpty()){
countBlankLine++;
}else{
countCodeLine++;
}
countTotalLine++;
}
System.out.println("注释行数:"+countAnnotation);
System.out.println("代码行数:"+countCodeLine);
System.out.println("空行行数:"+countBlankLine);
System.out.println("总行数:"+countTotalLine);
}
}
结果
注释行数:14
代码行数:7
空行行数:7
总行数:28