如何計算儲存於文字檔案中程式的 Java 註釋數?


您可以使用 Scanner 類讀取檔案的內容,並且可以使用contains()方法查詢特定行中的註釋。

示例

import java.io.*;
import java.util.Scanner;
public class FindingComments {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(new File("HelloWorld"));
      String input;
      int single = 0;
      int multiLine = 0;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         if (input.contains("/*")) {
            multiLine ++;
         }
         if(input.contains("//")) {
            single ++;
         }
      }
      System.out.println("no.of single line comments ::"+single);
      System.out.println("no.of single line comments ::"+multiLine);
   }
}

檔案 HelloWorld 的內容 −

Public class SampleProgram{
   /* This is my first java program.
      * This will print ‘Hello World’ as the output
   */
   Public static void main(String args[]){
      //Prints Hello World
      System.out.println("Hello World");
   }
}

輸出

no.of single line comments ::1
no.of single line comments ::1

更新日期:16-6-2020

413 瀏覽量

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.