如何计算Java文件中的注释行?

0 投票
2 回答
665 浏览
提问于 2025-04-18 00:09

这是我用来计算Java文件中不同代码行数量的一部分代码。在大多数情况下,这段代码能正确计算行数。但是如果注释的格式是这样的:

/* .......

*.......

*/

那么它会把这个注释块只算作两行。

        for eachLine in allLines:
            if eachLine != " " :
                eachLine = eachLine.replace(" ",""); #remove space
                eachLine = self.trim(eachLine);      #remove tabIndent
                if  (iscomment==False):
                    if(eachLine.strip().startswith("//")): #LINECOMMENT 
                        commentCount += 1;
                    if eachLine == "":
                        blankCount += 1;
                    if(eachLine.strip().startswith("/*")):
                        commentCount += 1;
                        if(not eachLine.strip().endswith("*/")):
                            iscomment=True
                else :
                    commentCount += 1;
                    if(eachLine.find("*/")):
                        iscomment=False
            lineCount = lineCount + 1;
        codeCount=lineCount-commentCount-blankCount

2 个回答

0
if(eachLine.find("*/")):

失败时返回的是 -1,而不是 false。

http://docs.python.org/2/library/string.html

1

你可以考虑使用正则表达式

import re

comments = re.findall('#.*?\n', allLines)
for item in re.findall('/\*.?*\*/', allLines):
    for row in item.split('\n'):
        comments.append(row)
print(len(comments))

大概是这样的,我在一个很简单的项目上试过,结果能正确获取到需要的行数。

撰写回答