有没有其他方法可以用来读取代码中的行以执行 readLine() 的功能?
Is there any other method I can use to read lines in my code to perform the function of a readLine()?
我正在编写一个代码来计算除注释和空行之外的代码行数,但我不知道用什么来代替带有文本变量的 readLine() 方法,因为它仅用于缓冲读取器 class。我不想使用 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() 与我应该做的不相关,因为它给出了一个错误,我已经写了 commentBegan()、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
}
}
用 line.separator
拆分 text
会 return 其中的所有行,存储在 array
中。遍历它并在那里使用你自己的逻辑。
我正在编写一个代码来计算除注释和空行之外的代码行数,但我不知道用什么来代替带有文本变量的 readLine() 方法,因为它仅用于缓冲读取器 class。我不想使用 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() 与我应该做的不相关,因为它给出了一个错误,我已经写了 commentBegan()、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
}
}
用 line.separator
拆分 text
会 return 其中的所有行,存储在 array
中。遍历它并在那里使用你自己的逻辑。