如何计算存储于文本文件中程序的 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
广告