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

Why is the first line of my file not being counted?

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

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

}
}

test1.txt

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.

输出

What file would you like to count the lines of code for?
Counting lines in test1.txt...
// 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.
3

从您的代码中删除这一行:

String line = reader.readLine();

基本都是看行。稍后你又在 while 条件中有 'while ((line = reader.readLine()) != null)',所以你总共读取了 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;
        }