Почему первая строка моего файла не учитывается?
Я пытаюсь создать программу, которая считает строки кода, где закомментированные строки не включены. Я пришел с приведенным ниже кодом, и он почти полностью работает, однако, когда получает строки из файла, кажется, что пропускается первая строка. Любая помощь будет принята с благодарностью!
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
2 ответа
Удалите эту строку из вашего кода:
String line = reader.readLine();
Это в основном читает строку. И позже у вас снова будет "while ((line = reader.readLine ())! = Null)" внутри условия while, так что вы читаете всего 2 строки, но только начинаете обработку со второй строки.
Как сказал @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;
}