0

我有一个Java程序,代码如下:

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();

  }}}

我想添加一段代码,以便如果一行以 /* 开头并以 */ 结尾,它可以忽略行数。此外,如果一行仅包含 ; 和 } 它也应该忽略这些行。我怎样才能做到这一点?

4

1 回答 1

0

在您的 while 循环之外,您需要首先创建一个变量来计算所有被忽略的行。

int ignoredLines = 0;

在您的 while 循环中,您可以添加以下条件:

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() - ignoredLines);

startsWithendsWithequalsString课堂上找到。

于 2012-10-27T20:11:36.447 回答