javacloc

Counting number of comments in java


I'm developing a tool to analyse and give some statistics about other people's source code, the tool will be able to recognize many things in the code! Right now am stuck at counting the number of comments on the code, my current code is:

 public static void main(String[] args) {

    String line = "";
    int count = 0;
    try {
        BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
        while ((line = br.readLine()) != null) {
            if (line.startsWith("//")) {
                count++;
            } else 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);
}

To check the code, I am using a test file. But the code is giving me the wrong result in both files, for example; I am getting three in the following file

Yes
//comment
yes
yes
/*
if
random
test
test
*/

While the answer should be two comments!

In the following file, it's showing me that I have five comments while I still actually have two

Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/

Solution

  • I think you have a problem in that comments can occur inside or at the end of a line as well...

    public static void main(String[] args) {
    
        String line = "";
        int count = 0;
        try {
            BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
            while ((line = br.readLine()) != null) {
                if (line.contains("//")) {
                    count++;
                } else if (line.contains("/*")) {
                    count++;
                    while (!line.contains("*/") && !(line = br.readLine()).contains("*/"));
                }
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        System.out.println("count=" + count);
    }
    

    Of course the problem here is what if the "//", "/* " or "*/" sequences occur within quoted text....?