- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to count Java comments of a program that is stored in a text file?
You can read the contents of a file using the Scanner class and You can find the comments in a particular line using contains() method.
Example
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); } }
Contents of the file 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"); } }
Output
no.of single line comments ::1 no.of single line comments ::1
Advertisements