开发者

How to count comment (single & multiple) lines in java?

I am doing project in Java. In that I am having one part in which, I have to identify the single, mul开发者_Go百科tiple comments and total no of comments in the program. I am in need of your guidance to count the no of single line comment, multiple line comment and total no comment lines in java.


If you just want a summary of the line count with regards to comments and code, look at CLOC. Point it at a source directory, i.e.:

cloc src

...and it'll display a summary for you.

CLOC also deals with the corner cases that make it difficult to do this problem yourself - multiline comments, comment looking lines within strings and so on. The following:

package test;

public class Main {

/**
 * A javadoc comment.
 * @param args
 */
public static void main(String[] args) {
    System.out.println("/* This isn't a comment */");
    /* This is a comment */
    //Comment
    System.out.println("//Not comment");
}
//Comment
}

CLOC gives 2 blank lines, 7 comment lines, and 7 code lines.

Yes, you could write something yourself in Java but unless this is a specific homework question (in which case it should be tagged as such) why reinvent the wheel? You'd need to deal with lots of corner cases, do lots of tests to make sure it worked, compare it against existing tools etc. and there's really no point in doing that when you've got something that does the job well already.


Here's a link to an assignment that I did for the same question. Hope this helps.

Note: It is not complete, cos it does not count the case of strings in java(within double quotes) that contain double quotes preceded by escape characters(like "/\"/") as line of code, but rather it counts it as a comment. This still has to be resolved.

http://bit.ly/PDasu9

Here is the explanation :-

Note :- This program is not optimized for performance, performance is not an attribute i care about here. I chose not to use Pattern.compile() among many other decisions.

I count the empty lines, comment lines and lines of code separately.

if there is any sentence which has a some tabs or just spaces, they are counted as
empty lines. They match with the regular expression \s*
\s - any whitespace character (\n\t\b)
 * - this means there can be any number of whitespace characters


comment lines are the ones that match any of the following conditions :-
1) have a // outside of a string
2) have a /* some comment */
3) have a /* but the '*/' is not found on the same line

The regular expression for the above can be found inside the code!

Lines of code are the ones that end in ')' , '}' , '{' or ';' (one problem with this approach is that it does not count lines that have code followed by comment as a line of code)

The summary of these three types of lines are provided by this program.


It works for me . It counts the total number of Single and multiple line comments in a java file.

public class CountComment {

    public static void main(String[] args) throws IOException {
        try {
            String str;
            BufferedReader f = new BufferedReader(new FileReader("a.java"));
            LineNumberReader l = new LineNumberReader(f);
            int numberline = 0;
            int count = 0;
            while ((str = l.readLine()) != null) {
                numberline++;
                if (str.startsWith("/*")) {
                    while ((str = l.readLine()) != null) {
                        count++;
                        if (str.endsWith("*/")) {
                            count++;
                            break;
                        }
                    }
                }
                else if(str.startsWith("//")){
                    count++;
                }
            }
            System.out.println("" + count);
        } catch (FileNotFoundException e) {
            System.out.println("file not found");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Have a look at StreamTokenizer


In Java You have two type of comments:

// - Line comment

/* */ - Block comment.

Basing on this you can make simple assumptions:

  • if in line exist "//" then this line has at le one comment.

  • if in line exist "/*" a comment block has been opened.

  • if comment block is open(found) search for closing tag "*/".

So Your task is to check each line in file for those assumptions.


//Below is the working code 

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CountComment {

    public static void main(String[] args) {
        String line="";
        int count=0;
        try {
            BufferedReader br=new BufferedReader(new FileReader("./src/numbers/comment.txt"));
                while((line=br.readLine())!=null)
                {
                    if(line.startsWith("//"))
                        count++;
                    if(line.startsWith("/*"))
                    {
                        count++;
                        while(!(line=br.readLine()).endsWith("'*\'"))
                        {
                        count++;
                        break;
                        }
                    }

                }
                br.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
             catch (IOException e) {
                e.printStackTrace();
            }

        System.out.println("count="+count);
        } 


    }


For one of my class assignments I wrote a simple java code which does this task. https://github.com/chetanpawar0989/CommentAnalysis

I created this file before but I recently added to github. This program runs on one file and line by line. It takes one imput parameter on runtime filename.java

For example, to run this program: java CommentAnalysis filename.java

It counts single line (//) as well multi-line comments (/* ... */).

I tried to cover different comment scenarios as mentioned in this file.

I have also written my assumptions about my implementation in readme, but they should not be much difficult to change as per individual requirements. Please check it out and let me know if I am missing any comment scenario here.


I tried it and it works very well. With the code below, you will have to check each line:

                if (isEmpty(s) || s.IndexOf("\"//\"") != -1 || s.IndexOf("\"/*\"") != -1|| s.IndexOf("\"*/\"") != -1) continue;
                if (s.IndexOf("/*") != -1) checkCML = true;
                if (s.IndexOf("*/") != -1) checkCML = false;

                if (s.IndexOf("/*") != -1 && s.IndexOf("*/") != -1) ++commentLine;

                if (s.IndexOf("//") != -1 || checkCML) ++commentLine;


My answer would be:

public int countCommentLines(File file) throws IOException {
    BufferedReader input = new BufferedReader(new FileReader(file));
    int comments = 0;
    String line;
    while ((line = input.readLine()) != null) {
        line = line.trim();
        System.out.println(line);
        if (line.startsWith("//")) {
            //single line
            comments++;
        } else if (line.startsWith("/*")) {
            /* multiline
             * like this
             *  */
            comments++;
            while (!line.endsWith("*/")) {
                line = input.readLine().trim();
                comments++;
            }
        } else if (line.contains("/*")) { /* comments
        like this
        be careful with /* haha
        */
            Deque<Character> stack = new ArrayDeque<Character>();
            boolean hasStartOfComment = false;
            for (int i = 0; i < line.length() - 1; ++i) {
                if (stack.isEmpty() && line.charAt(i) == '/' && line.charAt(i + 1) == '*') {
                    // Yes this is the start of a block comment
                    hasStartOfComment = true;
                    break;
                } else if (line.charAt(i) == '\\'
                        && line.charAt(i + 1) == '\"' || line.charAt(i + 1) == '\'') {
                    // Well, it's escaped character
                    i++;
                    continue;
                } else if (line.charAt(i) == '\'' || line.charAt(i) == '\"') {
                    if (!stack.isEmpty() && stack.peek() == line.charAt(i)) {
                        stack.pop();
                    } else {
                        stack.push(line.charAt(i));
                    }
                    continue;
                }
            }
            if (!hasStartOfComment) {
                continue;
            }

            while (!line.endsWith("*/")) {
                line = input.readLine().trim();
                comments++;
            }
        }
    }
    return comments;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜