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

标签 java lines-of-code

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

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

}
}

测试1.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 行,但只从第二行开始处理。

关于java - 为什么我的文件的第一行没有被计算在内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109491/

相关文章:

java - 如何使用 Unirest 将数据从 Vaadin 发布到 Vertx?

java - 如何解决错误 : java. lang.BootstrapMethodError : java. lang.NoClassDefFoundError: io/vertx/core/Promise

git - 使用 Git merge 选定的代码行?

bash - 如何计算源代码中的行数

linux - 使用 Bash 统计我编写的代码行数

java - 在 GWT 的标签上显示所需的指示器

java - Jenkins 发布构建延迟

java - imageView 中图像的新尺寸

php - codeigniter 中的 Controller 性能

open-source - 如何根据 cloc.. 中的后缀忽略文件?