Counting number of comments in java

3k views Asked by At

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
/*
*/
6

There are 6 answers

9
m-albert On BEST ANSWER

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....?

6
Durandal On

The whole approach is flawed. You need to parse the source file properly, at least you need to keep track properly of quotes and nesting of "/*". Note that any comment character combination can appear inside statements like:

 System.out.println("// this is *not* a line comment");
 String s = "*/ this is not the end of a block comment";

and so on. Then there is the weird behavior with character escape sequences being processed before the file is interpreted:

    \u002F* this is a valid comment */

Its not that easy to determine what is a comment and whats not :) I strongly suggest you look for an open source parser solution for java sources.

3
Youssef NAIT On

I haven't tested your code however, I believe this should work :

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())!=null && !line.endsWith("'*\'"));
            }
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

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

When you meet the /* you should increment the counter and skip the comment section.

1
Koko Kondeti On
package com.usaa.training;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CommentsReading {
public static void main(String[] args) {

    String line = "";
    int number_of_blocks = 0;
    int comment_count = 0;
 int line_count = 0;
 int TODO = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
    try {
        File file = new File("C:\\code\\InvolvedPartyBasicInfoMapper.java");
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {
    line_count++;
            ;
            if (line.contains("//")) {
                 if (line.contains("TODO")){
                     TODO++;
                 }
                comment_count++;
        single_comment_count++;
            } else if (line.contains("/*") ) 
            {
                if (line.contains("TODO")){
                 TODO++;
             }
                comment_count++;
        multiple_comment_count++;
      if (line.endsWith("*/"))
      {
          break;
      }

                while (!(line = br.readLine()).endsWith("'*/'") )
                {
                    line_count++;
                    comment_count++;
            multiple_comment_count++;
            if (line.endsWith("*/"))
            {
                number_of_blocks++;
                break;
            }


                }
            }
        }
        br.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Total # of Lines  = " + line_count);
    System.out.println("Total # of Comment Lines= " +comment_count);
 System.out.println("Total # of Single line Comments= " +single_comment_count );
 System.out.println("Total # of Comment lines with Block Comments = " +multiple_comment_count );

    System.out.println("Total # of Block line Comments = " +number_of_blocks);

    System.out.println("No of TODO's  = " +TODO);
}
}
1
Koko Kondeti On
    enter code here
public class FilterInputStreamDemo {
public static void main(String[] args) {

    String line = "";
    int comment_count = 0;
 int line_count = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
    try {
        BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
        while ((line = br.readLine()) != null) {
    line_count++;
            if (line.startsWith("//")) {
                comment_count++;
        single_comment_count++;
            } else if (line.startsWith("/*")) {
                comment_count++;
        multiple_comment_count++;
                while (!(line = br.readLine()).endsWith("'*\'")) {
                    comment_count++;
            multiple_comment_count++;
                    break;
                }
            }
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("comment_count=" + comment_count);
}
}
0
waqas ali On

Guys here is a easy solution. Just download the cloc software from this link for windows. This software support every language & can accept folder of files also. Put your folder and cloc in same place and open cmd type this command

cloc-(version no).exe (folder name)
cloc-1.64.exe main

and have the no of lines, blank line and total no of lines in the code.

RESULTS:

For more detail see this: http://cloc.sourceforge.net/