Abubakar Oluyinka
Abubakar Oluyinka

Reputation: 351

Is there any other method I can use to read lines in my code to perform the function of a readLine()?

I am writing a code to count the lines of code with the exception of comments and empty lines but I am stuck at what to use in place of readLine() method with the text variable as it is used only with the BufferedReader class. I do not want to use BufferedReader. I want it to remain String. What can I do to solve this problem?

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) {}

The text.readLine() that I wrote above does not correlate with I should be done as it is giving an error, I have witten the full code for commentBegan(), commentEnd(), and isSourceCodeLine() methods. All I just need is to solve the problem of readLine() method.

Upvotes: 1

Views: 159

Answers (1)

aran
aran

Reputation: 11900

My suggestion is to identify the lines before the loop, and change its mechanism:

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
    }

}

Splitting the text by the line.separator would return all lines inside it, stored in an array. Iterate through it and use your own logic there.

Upvotes: 1

Related Questions