简体   繁体   English

如何计算java中的注释(单行和多行)行?

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

I am doing project in Java.我正在用Java做项目。 In that I am having one part in which, I have to identify the single, multiple 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.我需要您的指导来计算 java 中单行注释、多行注释和总无注释行的数量。

If you just want a summary of the line count with regards to comments and code, look at CLOC .如果您只想要关于注释和代码的行数摘要,请查看CLOC Point it at a source directory, ie:将其指向源目录,即:

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. CLOC 还处理使自己难以解决此问题的极端情况 - 多行注释、字符串中的注释行等。 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. CLOC 给出了 2 个空行、7 个注释行和 7 个代码行。

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?是的,你可以用 Java 自己写一些东西,但除非这是一个特定的家庭作业问题(在这种情况下它应该被标记为这样),为什么要重新发明轮子? 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.注意:它不完整,因为它不计算 java 中包含以转义字符开头的双引号(如“/\\”/”)作为代码行的字符串(双引号内)的情况,而是计算它作为评论。这仍然需要解决。

http://bit.ly/PDasu9 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.它计算 java 文件中单行和多行注释的总数。

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();
        }
    }
}
//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.对于我的一个课堂作业,我写了一个简单的 java 代码来完成这个任务。 https://github.com/chetanpawar0989/CommentAnalysis https://github.com/chetanpawar0989/CommentAnalysis

I created this file before but I recently added to github.我之前创建了这个文件,但我最近添加到了 github。 This program runs on one file and line by line.该程序在一个文件上逐行运行。 It takes one imput parameter on runtime filename.java它在运行时filename.java上需要一个输入参数

For example, to run this program: java CommentAnalysis filename.java例如,运行这个程序: 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.请检查一下,如果我在这里遗漏了任何评论场景,请告诉我。

In Java You have two type of comments:在 Java 中,您有两种类型的注释:

// - 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.所以你的任务是检查文件中的每一行是否有这些假设。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM