我正在编写代码以对代码行进行计数(注释和空行除外),但由于文本变量仅与BufferedReader类一起使用,因此无法使用带文本变量的readLine()方法。我不想使用BufferedReader。我希望它保持字符串形式。我该怎么办才能解决这个问题?
public static int count(String text) {
int count = 0;
boolean commentBegan = false;
String line = null;
while ((line = text.readLine()) != null) {
line = line.trim();
if ("".equals(line) || line.startsWith("//")) {
continue;
}
if (commentBegan) {
if (commentEnded(line)) {
line = line.substring(line.indexOf("*/") + 2).trim();
commentBegan = false;
if ("".equals(line) || line.startsWith("//")) {
continue;
}
} else
continue;
}
if (isSourceCodeLine(line)) {
count++;
}
if (commentBegan(line)) {
commentBegan = true;
}
}
return count;
}
private static boolean commentBegan(String line) {}
private static boolean commentEnded(String line) {}
private static boolean isSourceCodeLine(String line) {}
我上面编写的text.readLine()与我无关,因为它给出了错误,我应该这样做,我已经用了wittyBegan(),commentEnd()和isSourceCodeLine()方法的完整代码。我只需要解决readLine()方法的问题。
我的建议是识别循环之前的行,并更改其机制:
public static int count(String text) {
int count = 0;
boolean commentBegan = false;
String[] lines = text.split(System.getProperty("line.separator"));
for (String line:lines) {
//your logic here
}
}
胀裂text
通过line.separator
将返回它里面的所有线路,存储在array
。遍历它并在那里使用您自己的逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句