为什么我的文件的第一行没有被计算在内?

时间:2016-01-31 01:58:31

标签: java loc

我正在尝试创建一个计算代码行的程序,其中不包含注释行。我已经提出了下面的代码,它几乎完全正常工作,但是当从文件中获取字符串时,它似乎正在跳过第一行。任何帮助将不胜感激!

char str[] = "Hello World";
printf("%c", str[0]);

test1.txt的

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;

public class locCounter 
{

public locCounter(String filename) 
{
    System.out.println("Counting lines in " + filename + "...");
}

public static void main(String[] args)  throws FileNotFoundException
{
    boolean isEOF = false;

    System.out.println( "What file would you like to count the lines of code for?" );
    String programName = "test1.txt";
    //System.out.println(programName);

    locCounter countLines = new locCounter(programName);
    try ( BufferedReader reader = new BufferedReader( new FileReader( programName )))
    {
        String line = reader.readLine();
        int counter = 0;
        while ((line = reader.readLine()) != null)
        {
            line = line.trim();
            System.out.println(line);
            if (line.startsWith("//"))
            {
                counter = counter;
            }
            else
            {
                counter = counter + 1;
            }
        }
        System.out.println(counter);
        reader.close();
    }
    catch (FileNotFoundException ex)
    {
        System.out.println("The file was not found in the current directory.");
    }
    catch (IOException e)
    {
        System.exit(0);
    }

}
}

输出

This file has one line of code
    // This comment should not count
        This file now has two lines of code
    // Another comment that shouldn't be counted
}
A total of 4 lines should be counted.

2 个答案:

答案 0 :(得分:2)

从代码中删除此行:

String line = reader.readLine();

它基本上读取了这一行。后来又在' while((line = reader.readLine())!= null)' 再次在while条件中,所以你总共读了2行,但只从第二行开始处理。

答案 1 :(得分:2)

AS @admix已经说过,你的问题是你应该替换这行代码

String line = reader.readLine();

String line;

到目前为止,您的问题已经解决了。 正如我所看到的,您使用JDK7,因此您可以使用更少的行来编写读取文件代码。

    Path path = Paths.get(programName);
    try {
        try (BufferedReader reader = Files.newBufferedReader(path)){
            String line;
            while ((line = reader.readLine()) != null) {
                //process each line in some way
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

甚至更干净的版本

    Path path = Paths.get(programName);
    try {
        List<String> lines = Files.readAllLines(path);
        for (String line : lines) {
            //process each line in some way
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

另外,如果删除那些行,你的程序会更优雅,这是不必要的。

       if (line.startsWith("//"))
        {
            counter = counter;
        }
相关问题