user5923402 user5923402 - 6 months ago 20
Java Question

Counting number of comments in java

I'm developing a tool to analyse and give some statics about your 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; am getting 3 in the following file

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


while the answer should be 2 comments !!

in the following file, its showing me that i have five comments while I still actually have 2

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


so what can I do now?

Thanks

so what can I do now?

Thanks

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