gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:00:48 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com