1. 程式人生 > >給定一Java原始碼檔案,統計其註釋行數,空行行數數,程式碼行數及總行數

給定一Java原始碼檔案,統計其註釋行數,空行行數數,程式碼行數及總行數

規定:一行上既有程式碼又有註釋算程式碼行數(例如: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