【问题标题】:LineCount program in java. ignoring some lines in countingJava 中的 LineCount 程序。忽略计数中的一些行
【发布时间】:2012-10-27 20:06:37
【问题描述】:

我有一个 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();

  }}}

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

【问题讨论】:

  • 查看使用字符串方法来查看行的开头和结尾。 String API 将列出可用的方法,并且方法名称对于您的目的来说是不言自明的。换句话说,如果你看,你会很快找到重要的方法。

标签: java line-count


【解决方案1】:

在您的 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);

startsWithendsWithequals 位于 String 类中。

【讨论】:

  • "如果一行包含only",应该翻译成equals而不是contains
  • 这并不能解决 OP 的问题。他想排除包含 ONLY 的字符串;和},而不是任何包含这些字符的字符串。 @dan您的解决方案也不起作用,因为一行可能包含多个 ;或 } 或两者的某种组合
  • @drewhannay 你是对的 :)。为此,他可以将这两个 equals 替换为:nextLine.trim().matches("[};]+")
  • @dan,我正在使用您的解决方案。我才意识到我的错误。
  • 谢谢亲爱的......精英绅士。为您提供帮助
猜你喜欢
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
相关资源
最近更新 更多