import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * @author geoffreytowell * A small program to count the number of actual code lines... * excluding comments and blank lines * It still counts lines with only one character because I think it should */ public class Main { /* * Method comment */ public static void main(String[] args) { String filename; if (args.length > 0) filename = args[0]; else filename = "/Users/geoffreytowell/eclipse-workspace/RealLineCount/src/Main.java"; Scanner inScanner=null; // inline comment try { inScanner = new Scanner(new File(filename)); } catch (FileNotFoundException fex) { System.err.println("No such File" + filename); } int lineCount =0; boolean inBlock=false; while (inScanner.hasNextLine()) { String line = inScanner.nextLine().replace(" ", "").replace("\t", ""); if (line.contains("/*") && line.contains("*\n")) { // this still is not quite correct. But it is closer and al least // does not cause the code reader to skip over this line inBlock=true; } else if (inBlock && line.contains("*/")) { inBlock=false; } else if (line.contains("//")) { if (!line.substring(0,2).equals("//")) { lineCount++; } } else if (line.length()>0) { if (!inBlock) lineCount++; } //System.out.println(lineCount + " " + line); } if (inScanner!=null) inScanner.close(); System.out.println(lineCount); } }