我编写了一个 java 程序,它扫描并查找可执行代码行 (ELOC)、空代码行 (BLOC) 和注释 (CLOC),仅适用于 java 和 c++ 代码。以下是我的代码:
if(extension.contains("java") || extension.contains("c++"))
{
Scanner input = new Scanner(fileObject);
while(input.hasNext())
{
String s = input.nextLine();
if(s.length()==0)
{
bloc++;
}
else if(s.contains("/*") || s.startsWith("/*"))
{
cloc++;
while(!s.contains("*/"))
{
cloc++;
s = input.nextLine();
}
}
else if(s.contains("//"))
{
cloc++;
}
else
{
eloc++;
}
}//while
System.out.println("ELOC: "+(eloc));
System.out.println("Blank Lines: "+bloc);
System.out.println("Comment Lines: "+cloc);
}
我运行了不同的 java 和 c++ 源代码,但它并不总是给出正确答案。我该怎么做才能让它变得更好?有没有我可以使用的在线 java 代码?
对于这个问题,我只计算可执行的代码行数。如果一行如下所示:
int x=0;//some comment
那么上面这一行应该算作一个可执行行。以下是我更新的代码:
String extension=getExtension(fileObject.getName());
if(extension.contains("java") || extension.contains("c++"))
{
Scanner input = new Scanner(fileObject);
String s;
while(input.hasNext())
{
s = input.nextLine().trim();
eloc++;
if(s.equals(""))
{
bloc++;
}
if(s.startsWith("//"))
{
cloc++;
}
if(s.contains("/*") && !s.contains("*\\"))
{
cloc++;
while(!s.contains("*/"))
{
cloc++;
eloc++;
s = input.nextLine();
}
}
else if(s.contains("/*") && s.contains("*\\"))
{
cloc++;
}
}
System.out.println("Total number of lines: "+eloc);
System.out.println("ELOC: "+(eloc-(cloc+bloc)));
System.out.println("Blank Lines: "+bloc);
System.out.println("Comment Lines: "+cloc);
}
任何意见/建议将不胜感激..谢谢!
最佳答案
在 Unix 系统上,您可以简单地使用 cloc
.这将为您提供以下输出:
src$ cloc .
51 text files.
51 unique files.
285 files ignored.
http://cloc.sourceforge.net v 1.53 T=0.5 s (82.0 files/s, 5854.0 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Java 39 618 119 2145
XML 2 8 0 37
-------------------------------------------------------------------------------
SUM: 41 626 119 2182
-------------------------------------------------------------------------------
代码行不包含注释或空格,但包含诸如方括号或使用 cloc for Java 的导入语句之类的内容。
还有其他可用的工具,但如果您只需要计算代码行数,这是最简单的。希望这会有所帮助。
关于Java - 查找可执行代码行的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015847/