【问题标题】:Is there any other method I can use to read lines in my code to perform the function of a readLine()?有没有其他方法可以用来读取代码中的行以执行 readLine() 的功能?
【发布时间】:2021-04-03 16:27:37
【问题描述】:

我正在编写一个代码来计算除 cmets 和空行之外的代码行数,但我被困在使用什么来代替带有 text 变量的 readLine() 方法,因为它仅与 BufferedReader 类一起使用.我不想使用 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() 方法的问题。

【问题讨论】:

  • 计算换行符的数量,这应该给你答案吧?
  • 是的。这正是我想要实现的目标。

标签: java string bufferedreader streamreader readlines


【解决方案1】:

我的建议是识别循环之前的行,并改变它的机制:

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 中。遍历它并在那里使用您自己的逻辑。

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2023-03-11
    • 2010-12-22
    • 1970-01-01
    • 2021-04-18
    • 2012-01-29
    • 2021-02-17
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多