I have a program in Java with the following code:
import java.io.*;
public class LineCountingProg
{
public static void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("d://MyFile.txt");
}
catch(FileNotFoundException e)
{
System.out.println("The source file does not exist. " +e );
}
LineNumberReader lineCounter = new LineNumberReader(new InputStreamReader(fis));
String nextLine = null;
try {
while ((nextLine = lineCounter.readLine()) != null) {
System.out.println(nextLine);
if ((nextLine.startsWith("/*") && nextLine.endsWith("*/"))
|| (nextLine.trim().matches("[{};]+"))) {
//This line needs to be ignored
ignoredLines++;
continue;
}
}
System.out.println("Total number of line in this file " + lineCounter.getLineNumber());
int fcounter = 0;
fcounter = lineCounter.getLineNumber()-ignoredLines ;
System.out.println("Total " +fcounter);
} catch (Exception done) {
done.printStackTrace();
}}}
I want to add a piece of code so it could ignore line counts if a line starts with /* and ends with */. Also if a line contains only ; and } it should be also ignore those lines. How can I do that?
Outside your while loop, you need to first create a variable to count all ignored lines.
Inside your while loop, you can add the following condition:
Finally:
startsWith
,endsWith
andequals
are found in theString
class.