Skip to content

Instantly share code, notes, and snippets.

@giuniu
Created October 10, 2012 22:22
Show Gist options
  • Save giuniu/3868876 to your computer and use it in GitHub Desktop.
Save giuniu/3868876 to your computer and use it in GitHub Desktop.
Javaコードのステップカウンター
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public enum StepCounter {
INSTANCE;
private static final Pattern BLOCK_COMMENT_START = Pattern.compile("^(.*)\\/\\*.*$");
private static final Pattern BLOCK_COMMENT_END = Pattern.compile("^.*\\*\\/(.*)$");
private static final Pattern LINE_COMMENT = Pattern.compile("^\\s*\\/\\/.*$");
public static class Result {
public final int allCnt;
public final int netCnt;
public final int commentCnt;
public final int emptyCnt;
private Result(int allCnt, int netCnt, int commentCnt, int emptyCnt) {
this.allCnt = allCnt;
this.netCnt = netCnt;
this.commentCnt = commentCnt;
this.emptyCnt = emptyCnt;
}
}
public static void main(String[] args) {
try {
FileReader reader = new FileReader(args[0]);
Result result = INSTANCE.analyze(reader);
System.out.println("all lines:" + result.allCnt);
System.out.println("net lines:" + result.netCnt);
System.out.println("comment lines:" + result.commentCnt);
System.out.println("empty lines:" + result.emptyCnt);
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
public Result analyze(Reader reader) throws IOException {
try (BufferedReader br = new BufferedReader(reader)) {
int allCnt = 0;
int netCnt = 0;
int commentCnt = 0;
int emptyCnt = 0;
boolean inBlockComment = false;
for (String line; (line = br.readLine()) != null; ) {
allCnt++;
if (line.trim().length() == 0) {
// 空行
emptyCnt++;
} else if (inBlockComment) {
// ブロックコメント中
Matcher matcher = BLOCK_COMMENT_END.matcher(line);
if (matcher.matches()) {
// ブロックコメント終了
inBlockComment = false;
if (matcher.group(1).trim().length() == 0)
// 実コードなし
commentCnt++;
else
// 実コードあり
netCnt++;
} else {
// ブロックコメント続行
commentCnt++;
}
} else {
// ブロックコメント外
Matcher matcher = BLOCK_COMMENT_START.matcher(line);
if (matcher.matches()) {
// ブロックコメント開始
inBlockComment = true;
if (matcher.group(1).trim().length() == 0)
// 実コードなし
commentCnt++;
else
// 実コードあり
netCnt++;
} else if (LINE_COMMENT.matcher(line).matches()) {
// 行コメント
commentCnt++;
} else {
netCnt++;
}
}
}
return new Result(allCnt, netCnt, commentCnt, emptyCnt);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment