I am trying to create a program that counts lines of code, where the commented lines are not included. I have come up with the code below, and its almost working completely, however when gets the strings from the file, it seems to be skipping the first line. Any help would be greatly appreciated!
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.
Output
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