Question

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?

Was it helpful?

Solution

Outside your while loop, you need to first create a variable to count all ignored lines.

int ignoredLines = 0;

Inside your while loop, you can add the following condition:

if ((nextLine.startsWith("/*") && nextLine.endsWith("*/"))
    || (nextLine.trim().matches("[};]+"))) {
  //This line needs to be ignored
  ignoredLines++';
  continue;
}

Finally:

System.out.println("Total number of line in this file " + lineCounter.getLineNumber() - ignoredLines);

startsWith, endsWith and equals are found in the String class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top