2  

範例下載

 

 

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Stack;
// Help class for Java source step count.
public class JavaSourceCount {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Please specified a file name");
System.exit(1);
}
counter(args[0]);
}
static int space;
static int comment;
static int total;
static int source;
static Stack<Character> sstack = new Stack<Character>();
public static void counter(final String fullfilename) throws Exception {
String filename = fullfilename;
// String c1s = "/*";
// String c2s = "//";
// String c1e = "*/";
BufferedReader fr = new BufferedReader(new FileReader(new File(filename)));
String line = "";
while ((line = fr.readLine()) != null) {
handler(line);
}
fr.close();
total = source + comment + space;
System.out.println(filename + "'s counter result is :");
System.out.println("total" + ":" + total);
System.out.println("source" + ":" + source);
System.out.println("comment" + ":" + comment);
System.out.println("space" + ":" + space);
}
public static void handler(String line) {
char[] ca = line.toCharArray();
boolean isSpace = true;
for (int i = 0; i < ca.length; i++) {
if (ca[i] == ' ') {
continue;
}
if (ca[i] == '\t') {
continue;
}
isSpace = false;
if (ca[i] == '/') {
if (sstack.empty()) {
// //
if (i + 1 < ca.length && ca[i + 1] == '/') {
comment++;
break;
}
// /*
if (i + 1 < ca.length && ca[i + 1] == '*') {
sstack.push(ca[i]);
break;
}
}
}
if (ca[i] == '*') {
if (!sstack.empty()) {
// */
if (i + 1 < ca.length && ca[i + 1] == '/') {
comment++;
while (!sstack.empty()) {
sstack.pop();
comment++;
}
break;
}
}
}
if (!sstack.empty()) {
sstack.push(ca[i]);
} else {
source++;
}
break;
}
if (isSpace) {
space++;
}
}
}

 

 

本文出自 “点点滴滴” 博客,请务必保留此出处http://kin111.blog.51cto.com/738881/1121259

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()