问题描述
我有兴趣编写一些代码来检测Java代码中的特殊情况,因为我们在同一行上有一些带有注释的代码。
int i = 10 //here is the comment
我希望能够使用Kotlin的File forEachLine方法检测到此类行。但是我不知道该怎么做。
我唯一能做的就是通过以下操作找到一行中包含注释的内容:
File(fileName).forEachLine {
if(it.contains("//")){
println("There is a comment!")
}
}
我对检测注释不感兴趣,只对那些在同一行上有代码和注释的行感兴趣。
注意:fileName是一个Java文件,例如:我们逐行读取的Test.java。
解决方法
您可以在文件的每一行上结合使用split
和filter
函数:
fun getCodeLinesWithComments(lines: ArrayList<String>): ArrayList<String> {
val codeLinesWithComments = arrayListOf<String>()
for (line in lines) {
if (line.split("//").filter { it.isNotEmpty() }.count() == 2) {
codeLinesWithComments.add(line)
}
}
return codeLinesWithComments
}